GroupingBy and sum with java lambda
public class Clazz { int type; int value; BigDecimal dValue; public Clazz(int type, BigDecimal dValue) { this.type = type; this.dValue = dValue; } public Clazz(int type, int value) { this.type = type; this.value = value; } public int getType() { return type; } public int getValue() { return value; } public BigDecimal getDValue() { return dValue; } }
List<Clazz> l = Arrays.asList( new Clazz(1,1), new Clazz(2,1), new Clazz(3,1), new Clazz(3,2), new Clazz(1,3)); l.stream().collect(Collectors.groupingBy(e -> e.getType(), Collectors.summingInt(e -> e.getValue()))).forEach((id, sum) -> System.out.println(id+"\t"+sum));
Output is:
1 4
2 1
3 3
List<Clazz> dl = Arrays.asList( new Clazz(1, new BigDecimal(1.1)), new Clazz(2,new BigDecimal(1.2)), new Clazz(3,new BigDecimal(1.3)), new Clazz(3,new BigDecimal(2.2)), new Clazz(1,new BigDecimal(3.3))); dl.stream().collect(Collectors.groupingBy(e -> e.getType(), Collectors.mapping(e -> e.getDValue(), Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)))) .forEach((id, sum)->System.out.println(id+"\t"+sum.setScale(2, RoundingMode.HALF_UP)));
Output is:
1 4.40 2 1.20 3 3.50