Video in progress

Strong Junior 🌊 Streams and lambdas

What does this code print to the console, and why?

List<String> names = List.of("ali", "vali", "soli");

names.stream()
     .peek(n -> System.out.println("ko'rildi: " + n))
     .map(String::toUpperCase);

System.out.println("tugadi");

Nothing is printed. peek and map are intermediate operations and there is no terminal operation, so the chain never runs at all.

📖 Answer

Only tugadi is printed.

A stream is lazy: peek and map only build a "plan", and nobody pulls elements through. The work starts only when a terminal operation is called. If you add .toList() at the end:

ko'rildi: ali
ko'rildi: vali
ko'rildi: soli
tugadi

There's one interesting case. Since Java 9, count() sometimes doesn't traverse the elements at all:

names.stream().peek(System.out::println).count();   // may print nothing

If the source size is known (SIZED) and there's no filter in between, the JDK takes the count straight from the list and peek is never called.

So don't put important logic (writing to a database, a counter) in peek. It's for debugging only, and the documentation says so too.