I have a Java class like
public class A {
private int id;
private BigDecimal amount;
}
I would like to group by id with java 8 several objects like this :
public class Main {
public static void main(String[] args) {
A a1 = new A(1, new BigDecimal("500.36"));
A a2 = new A(2, new BigDecimal("439.97"));
A a3 = new A(2, new BigDecimal("49.97"));
A a4 = new A(2, new BigDecimal("9.97"));
List<A> postings = new ArrayList<>();
postings.add(a1);
postings.add(a2);
postings.add(a3);
postings.add(a4);
List<A> brol = new ArrayList<>();
System.out.println("-----------------");
postings.stream()
.collect(Collectors.groupingBy(A -> A.getId(), Collectors.summingDouble(A->A.getAmount().doubleValue())))
.forEach((id, sum) -> brol.add(new A(id, BigDecimal.valueOf(sum))));
brol.forEach(System.out::println);
}
}
And the output is :
1 500.36
2 499.91
Which is exactly what I'm looking for. But, there is the Collectors.summingDouble
operation and I know that Double
is not suitable for currency operations.
So will I have problems with this method (working on money operations) or there is a way to do it with BigDecimal ?
You can use reducing
to perform the summing with BigDecimal
:
.collect(Collectors.groupingBy(A::getId,
Collectors.reducing(BigDecimal.ZERO,
A::getAmount,
BigDecimal::add)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With