I am trying to get following Map via Java 8
Class One {
String one;
List <Two> two;
}
Class Two {
BigDecimal bd;
}
How do I collect a Map which contains grouping by One.one i.e., first parameter of map. For second parameter of map sum of Two.bd.
This will do what you want:
This collects by
One.one
, transforming eachOne.two
to aBigDecimal
that is the sum of itsTwo.bd
attributes, then it reduces and sums again in case there are repeatedOne.one
in the list.EDIT:
First part of @Jorn Vernee's edited answer is exactly the same as my own's, so here I present another approach:
Here I'm using the overloaded version of
Collectors.toMap
, which takes care of collisions by using the supplied merge function (in this caseBigDecimal::add
).You can use this:
This will sum all the
bd
ofTwo
, and then also sum the sums forOne
s that have the sameone
.Although things would be simpler if Java8 had a flatMapping collector, one has been added to Java9:
Which would make: