Video in progress

Strong Middle 🌊 Streams and lambdas

This code gives different results on Java 8 and Java 17. Why?

List<String> names = List.of("Ali", "Vali", "Gani");
long n = names.stream()
        .peek(s -> System.out.println("ko'rdim: " + s))
        .count();
System.out.println(n);

Since Java 9, if count() knows the source size in advance (SIZED) and no operation in between changes the size, it doesn't run the pipeline at all. So the code inside peek is never called.

📖 Answer

On Java 8 you get three "ko'rdim" lines and then 3. On Java 17 just 3.

The reason: the spliterator of List.of(...) has the SIZED flag, and peek and map don't change the size. The JDK considers the answer for count() known exactly from estimateSize() and doesn't traverse the elements. The Javadoc says this openly: if the result can be computed directly from the source, the implementation may not execute the pipeline.

If you add a filter to the pipeline, the size becomes unknown and peek runs again.

The lesson: don't put business logic in peek. Its Javadoc says "mainly to support debugging". Someone writes peek(order -> order.markProcessed()), everything works, then one day the terminal operation is swapped for count() or the JDK is upgraded, and the side effect silently disappears.

If you need a side effect, make it explicit: forEach or a plain for. If you need to change data, return a new object with map.