hotmeatballsoup
hotmeatballsoup

Reputation: 605

Summing a nested property using the Java Stream API

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?

Upvotes: 3

Views: 1189

Answers (1)

Samuel Philipp
Samuel Philipp

Reputation: 11042

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.

Upvotes: 5

Related Questions