Search code examples
javajava-streambigdecimal

Summing up BigDecimal in a map of list of objects in Java


I'm stuck with some elegant ways to get a summation of BigDecimals 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 bs in myMap. Looking for some elegant ways to do this in Java, may be using streams?


Solution

    1. Stream the values of the Map.
    2. Use flatMap to flatten the stream of lists of BigDecimals to a stream of BigDecimals.
    3. Use map to extract the BigDecimals.
    4. Use 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.