user2220232
user2220232

Reputation: 71

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?

Upvotes: 2

Views: 7442

Answers (2)

rgettman
rgettman

Reputation: 178303

  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.

Upvotes: 9

Karol Dowbecki
Karol Dowbecki

Reputation: 44970

BigDecimal sum = myMap.values()
    .stream()
    .flatMap(Collection::stream)
    .map(Obj::getB)
    .reduce(BigDecimal.ZERO, BigDecimal::add);

Upvotes: 3

Related Questions