@Getter public class Dish { BigDecimal price; }
I need to calculate the total price of all ordered dishes, but I fail to write the reduce method. This is a method signature ( argument has a map of Dish and how many times it was ordered ).
So it must be something like this sum of every dish.getPrice * dishQuantaty
private BigDecimal getOrderTotalPrice(Map<Dish, Integer> dishQuantityMap) { }
The fail-code I was asked about
return dishQuantityMap.entrySet().stream() .reduce(BigDecimal.ZERO, (dishIntegerEntry) -> dishIntegerEntry.getKey().getPrice() .multiply(BigDecimal.valueOf(dishIntegerEntry.getValue())));
Advertisement
Answer
Did you mean something like this:
private BigDecimal getOrderTotalPrice(Map<Dish, Integer> dishQuantityMap) { return dishQuantityMap.entrySet().stream() .map(d -> d.getKey().getPrice().multiply(new BigDecimal(d.getValue()))) .reduce(BigDecimal.ZERO, BigDecimal::add); }