3 ms·
The first point I won't refute. Some people like imperative style and that's fine. I personally don't and find the stream based approaches much simpler. As f
by davewritescode 5y ago
The first point I won't refute. Some people like imperative style and that's fine. I personally don't and find the stream based approaches much simpler.
As for your second point, you could easily add such functionality to the code with a stateful mapping operation that sets the price to 0 for every other item encountered. In your code, you'd have to add another pass of the loop or you'd have to stick the logic for computing the price inside your for loop.
Personally, I've found that decomposing problems into stream based pipelines makes it much easier to decorate additional functionality than imperative code but that's just my personal experience.
public PriceAndRows getPriceAndRows(Cart cart) {
DiscountApplier discounts = new DiscountApplier()
return cart.getProducts()
.entrySet()
.stream()
.map(CartRow::new)
.map(cartRow -> discounts.apply(cartRow)) // Stateful discount application logic
.collect(Collectors.teeing(
Collectors.reducing(BigDecimal.ZERO, CartRow::getRowPrice, BigDecimal::add),
Collectors.toList(),
PriceAndRows::new
));
}