Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fail to write the reduce method using Stream API

@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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  return   dishQuantityMap.entrySet().stream()
        .reduce(BigDecimal.ZERO,
                (dishIntegerEntry) ->
               dishIntegerEntry.getKey().getPrice()
                        .multiply(BigDecimal.valueOf(dishIntegerEntry.getValue())));

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading