Reputation: 625
Java 8 here. I have the following POJO:
@Getter
@Setter
public class Orderline {
private Integer qty;
private BigDecimal price;
private String productName;
}
I'm looking for a Stream-y way of iterating through a List<Orderlines>
and coming up with a subtotal
based on their individual quantities and prices. The "old" (pre-Stream) way of doing this would look like:
List<Orderline> orderlines = order.getOrderlines();
double sub = 0.0;
for (Orderline ol : orderlines) {
sub += ol.getQty() * ol.getPrice();
}
BigDecimal subtotal = BigDecimal.valueOf(sub);
My best attempt at using Streams to accomplish this is:
BigDecimal subtotal = order.getOrderlines().stream()
.map(Orderline::getPrice)
.reduce(BigDecimal.ZERO, BigDecimal::add);
However this doesn't take their quantities into consideration. Any ideas how I can accomplish this?
Upvotes: 1
Views: 196
Reputation: 1092
You could use
map(x->x.getPrice().multiply(BigDecimal.valueOf(x.getQty())))
in your second line.
Upvotes: 2