ExampleDifficulty: Intermediate1 min

Streams Example: Filtering and Mapping a List of Orders

The same list built by a loop and by a pipeline, with no accumulator in the second.

A stream pipeline replaces a loop that builds a list: filter keeps the elements that match, map turns each one into something else, and toList collects the result. The references of every order over a hundred pounds, first as a loop:

java
List<String> big = new ArrayList<>();
for (Invoice i : invoices) {
    if (i.pence() > 10_000) {
        big.add(i.reference());
    }
}

And as a pipeline:

java
List<String> big = invoices.stream()
        .filter(i -> i.pence() > 10_000)
        .map(Invoice::reference)
        .toList();

The two produce the same list. What the second one removes is the accumulator and the mutation: there is no empty list to declare, nothing to add to, and no way to accidentally add in the wrong branch.

toList() on line 4 is the terminal operation (the last step, which produces a result and makes the stream run), and it is what makes the other two lines run at all. Delete it and this compiles into a stream nobody consumes.