Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing BigDecimals in streams API Collectors

My current attempt is based on double type class members:

public Client whoPaidTheMost() {

/*METHOD EXPLOITING STREAM API*/

return shopping.entrySet()
        .stream()
        .collect(Collectors.groupingBy(Map.Entry::getKey,
                Collectors.flatMapping(e -> e.getValue().entrySet().stream(),
                        Collectors.summingDouble(e->e.getKey().getPrize() * e.getValue())))) /*should be refactored*/
        .entrySet().stream()
        .max(Comparator.comparingDouble(Map.Entry::getValue))/*should be refactored*/
        .get()
        .getKey();
}

shopping is basically a map: Map<Client, Map<Product,Integer>>,

  • The outer Key represents the Client
  • The inner Key represents the Product
  • the inner maps value (Integer) reprents the number of specified product which belong to a specific client

Product class members are name, category, price (previously of double type) - want to refactor the provided code into one using price as a type of BigDecimal

How could I make this code work also for BigDecimals - ?

Basically I' ve refactored that arleady:

  Client client = shopping.entrySet()
            .stream()
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.flatMapping(e -> e.getValue().entrySet().stream(),
                            Collectors.mapping(e -> BigDecimal.valueOf(new Long(e.getValue())).multiply(e.getKey().getPrize()),
                                    Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)))))
            .entrySet().stream()
            .max((e1, e2) -> (e1.getValue().compareTo(e2.getValue())))
            .get()
            .getKey();

Still wondering if it's possible to refactor this without using: Collectors.mapping(e -> BigDecimal.valueOf(new Long(e.getValue())).multiply(e.getKey().getPrize()) before Collectors.reducing ?

like image 509
Ares02 Avatar asked Feb 03 '26 12:02

Ares02


1 Answers

If you are looking for a Collector that sums BigDecimals, this should work:

Collector<BigDecimal, ?, BigDecimal> collector 
    = Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
like image 90
Joe C Avatar answered Feb 06 '26 02:02

Joe C