Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 group by and BigDecimal

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 ?

like image 222
Grechka Vassili Avatar asked Aug 03 '17 08:08

Grechka Vassili


1 Answers

You can use reducing to perform the summing with BigDecimal:

.collect(Collectors.groupingBy(A::getId,              
                               Collectors.reducing(BigDecimal.ZERO, 
                                                   A::getAmount, 
                                                   BigDecimal::add)))
like image 155
Eran Avatar answered Oct 23 '22 05:10

Eran