Java 8 and BigDecimal Group

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 result:

1,500.36
2,499.91

That is what I am looking for. But there is the operation Collectors.summingDouble , and I know that Double not suitable for foreign exchange transactions. So will I have problems with this method (work with money transactions) or is there a way to do this using BigDecimal?

EDIT This method was found:

 postings.stream() //.collect(Collectors.groupingBy(A -> A.getId(), Collectors.summingDouble(A->A.getAmount().doubleValue()))) .collect(Collectors.groupingBy(A -> A.getId(), Collectors.reducing(BigDecimal.ZERO, A::getAmount, BigDecimal::add))) .forEach((id, sum) -> brol.add(new A(id, sum))); 
+5
source share
1 answer

You can use reducing to do the summation using BigDecimal :

 .collect(Collectors.groupingBy(A::getId, Collectors.reducing(BigDecimal.ZERO, A::getAmount, BigDecimal::add))) 
+8
source

Source: https://habr.com/ru/post/1270522/


All Articles