Modern Java 8+ Features · The Stream API

Streams: filter, map, collect

Describe what you want from a list as a pipeline. Watch each price travel through filter and map one at a time, and see that nothing runs until collect.

StreamBasicsDemo.java

import java.util.List;
import java.util.stream.Collectors;

public class StreamBasicsDemo {
    public static void main(String[] args) {
        List<Integer> prices = List.of(12, 45, 7, 30);

        List<Integer> withTax = prices.stream()
                .filter(p -> p >= 10)          // keep prices of 10 or more
                .map(p -> p + p / 10)          // add 10% tax
                .collect(Collectors.toList());  // gather the results into a list

        System.out.println(withTax + " from " + prices);
    }
}

Step by step

  1. Four prices.
  2. Line runs: List<Integer> withTax = prices.stream().
  3. filter, map and collect are only being set up here; no price has been checked yet.
  4. Line runs: .map(p -> p + p / 10) // add 10% tax.
  5. Java calls lambda$main$0(), with p = 12. It gets its own variables on the stack.
  6. collect starts pulling. The first price, 12, goes into filter: 12 >= 10, kept.
  7. 12 goes straight on into map: 12 + 1 = 13.
  8. Java calls lambda$main$1(), with p = 45. It gets its own variables on the stack. lambda$main$0() has finished, so its variables are gone.
  9. Java calls lambda$main$0(), with p = 7. It gets its own variables on the stack. lambda$main$1() has finished, so its variables are gone.
  10. The price 7 fails the filter…
  11. …so the next price, 30, is checked straight away.
  12. lambda$main$1() has finished, so its variables are gone.
  13. The value it returned, [13, 49, 33], is stored in withTax.
  14. It prints [13, 49, 33] from [12, 45, 7, 30].
  15. [13, 49, 33], and the original list is unchanged. Each item travelled the whole pipeline before the next one started.