I have a list of Author objects. And I need to generate a Map<String,Author> associating a key, which consists of concatenated transId and countryCode, with a value representing an aggregated Author object.
public static class Author {
String transId;
String countryCode;
Double currencyUSD;
Double exccessAmount;
// constructors, getters, setters, etc.
}
Consider the following example:
Author a1 = new Author("1111111", "US", 1000.00, 50.0);
Author a2 = new Author("1111111", "US", 1000.00, 50.0);
Author a3 = new Author("1111111", "US", 1000.00, 1000.00);
Author a4 = new Author("222222", "US", 1000.00, 1000.00);
Author a5 = new Author("222222", "US", 1000.00, 1000.00);
Author a6 = new Author("3333333", "US", 1000.00, 1000.00);
Author a7 = new Author("444444", "US", 1000.00, 1000.00);
List<Author> authors = List.of(
a1, a2, a3, a4, a5, a6, a7
);
Here there are several objects having same transId and countryCode, like a1, a2 and a3. I want to aggregate them by adding currencyUSD values in each group together, and also exccessAmount values.
My code:
public static void prepareList() {
List<Author> authors = // initializing the list
Map<String, Author> mapList2 = authors.stream()
.collect(Collectors.groupingBy(
authorObj -> authorObj.getTransId() + "_" + authorObj.getCountryCode(),
Collectors.reducing(
new Author("", "", 0D, 0D),
(x, y) -> {
y.setCurrencyUSD(Double.sum(y.getCurrencyUSD(), x.getCurrencyUSD()));
y.setExccessAmount(Double.sum(y.getExccessAmount(), x.getExccessAmount()));
return y;
})
));
}
I'm getting a NullPointerException in the collector while generating the map. How can I add a null-check to my code?
Exception in thread "main" java.lang.NullPointerException at Examples.App.lambda$1(App.java:206) at
java.base/java.util.stream.Collectors.lambda$reducing$42(Collectors.java:877) at
java.base/java.util.stream.Collectors.lambda$groupingBy$53(Collectors.java:1136) at
java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169) at
java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655) at
java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)