ExampleDifficulty: Intermediate1 min

Filtering and Mapping a List of Orders

The references of every order over a hundred pounds, as a list. The loop version and the pipeline version, side by side.

java
List<String> big = new ArrayList<>();
for (Invoice i : invoices) {
    if (i.pence() > 10_000) {
        big.add(i.reference());
    }
}
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, and it is what makes the other two lines run at all. Delete it and this compiles into a stream nobody consumes.