Video in progress
In what order does a stream process elements: is every element filtered first and then every element mapped?
No. Each element goes through the chain one at a time, "vertically": the first element through filter, then map, then the terminal operation; then the second element. Only stateful operations like sorted collect all the elements.
📖 Answer
You can see this for yourself:
Stream.of("a", "bb", "ccc")
.filter(s -> { System.out.println("filter " + s); return s.length() > 1; })
.map(s -> { System.out.println("map " + s); return s.toUpperCase(); })
.forEach(s -> System.out.println("forEach " + s));
filter a
filter bb
map bb
forEach BB
filter ccc
map ccc
forEach CCC
This is called loop fusion: the chain behaves like a single loop, and no intermediate lists are created. That's why short-circuit operations are efficient: findFirst doesn't read the rest at all once it finds the first matching element.
If you add sorted(), the picture changes. Sorting needs to know all the elements, so it first collects everything from the previous stage, sorts, and only then passes elements down. distinct() also keeps state, but it passes elements along without waiting.
The practical consequence: put filter before sorted, so fewer elements get sorted.
Sign up to mark studied questions and save your progress.