I have the following Java POJOs:
public class Order {
private List<OrderLine> orderLines;
private String name;
// ... lots of other fields
// Getters & setters & ctors down here
}
public class OrderLine {
private String productId;
private Integer quantity;
// Getters & setters & ctors down here
}
I'm trying to find a Java 8 "Streamy" way of grabbing the total quantity of all orderlines in an order. The "old" way of grabbing this count would look like this:
int totalQuantity = 0;
for (OrderLine ol : order.getOrderLines()) {
totalQuantity += ol.getQuantity();
}
My best attempt so far:
Integer totalQuantity = order.getOrderLines().stream().filter(ol -> ol.getQuantity());
I know this is wrong since its not iterating through the List<OrderLine> and summing each line's quantity, and it doesn't compile since filter(...) needs the expression to resolve to a boolean, not an int value.
Any ideas where I'm going awry?
You are looking for Stream.mapToInt(), which creates an IntStream and IntStream.sum(). You can try this:
int totalQuantity = order.getOrderLines().stream()
.mapToInt(OrderLine::getQuantity)
.sum();
This will sum up the total quality of all order lines from an order.
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