简体   繁体   中英

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

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM