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>>,
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 ?
If you are looking for a Collector that sums BigDecimals, this should work:
Collector<BigDecimal, ?, BigDecimal> collector
= Collectors.reducing(BigDecimal.ZERO, 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