I'm stuck with some elegant ways to get a summation of BigDecimal
s in a map. I know how to calculate the sum in a map of BigDecimal
but not a List of object with a BigDecimal
.
The structure of my objects are as below:
Class Obj {
private BigDecimal b;
// Getter for b, say getB()
}
Map<String, List<Obj>> myMap;
I need to get a sum of all b
s in myMap
. Looking for some elegant ways to do this in Java, may be using streams?
Map
.flatMap
to flatten the stream of lists of BigDecimal
s to a stream of BigDecimal
s.map
to extract the BigDecimal
s.reduce
with a summing operation.BigDecimal sum = myMap.values().stream()
.flatMap(List::stream)
.map(Obj::getB)
.reduce(BigDecimal.ZERO, (a, b) -> a.add(b) );
The Stream.reduce
method takes an identity value (for summing values, zero), and a BinaryOperator
that adds intermediate results together.
You may also use a method reference in place of the lambda above: BigDecimal::add
.