Summing a nested list using Java Stream API

hotmeatballsoup :

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?

Samuel Philipp :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122729&siteId=1