Need help for a case on Stream with groupingBy I would like to be able to group by 2 different fields and have the sum of other BigDecimal fields, according to the different groupings. Here is my entity :
public class Customer {
private String name;
private String type;
private BigDecimal total;
private BigDecimal balance;
// Setter, getter
}
Let's suppose I have as input this list:
Customer custa = new Customer("A", "STANDARD", new BigDecimal("1000"), new BigDecimal("1500"));
Customer custa1 = new Customer("A", "VIP", new BigDecimal("2000"), new BigDecimal("2500"));
Customer custb = new Customer("B", "STANDARD", new BigDecimal("3000"), new BigDecimal("3500"));
Customer custc = new Customer("C", "STANDARD", new BigDecimal("4000"), new BigDecimal("4500"));
Customer custa2 = new Customer("A", "VIP", new BigDecimal("1500"), new BigDecimal("2500"));
List<Customer> listCust = new ArrayList<>();
listCust.add(custa);
listCust.add(custa1);
listCust.add(custb);
listCust.add(custc);
listCust.add(custa2);
The result should be
[
{"A", "STANDARD", new BigDecimal("1000"), new BigDecimal("1500")},
{"A", "VIP", new BigDecimal("3500"), new BigDecimal("5000")},
{"B", "STANDARD", new BigDecimal("3000"), new BigDecimal("3500")},
{"C", "STANDARD", new BigDecimal("4000"), new BigDecimal("4500")}
]
I have a beginning of solution, below, but I block at the moment of adding a second aggregation to sum up the balance:
listCust.stream()
.collect(Collectors.groupingBy(Customer::getName
, Collectors.groupingBy(Customer::getType
, Collectors.reducing(BigDecimal.ZERO,Customer::getTotal,BigDecimal::add)))
)
.entrySet()