Sobes.tech
Senior

var list = List.of(5, 13, 34); list.stream() .map(x -> x % 10) .peek(System.out::println) .filter(x -> x > 3) .forEach(System.out::println); List<String> animals = List.of("dog", "cat", "parrot"); animals.stream() .sorted() .peek(item -> System.out.println(item)) .map(String::length); System.out.println(animals);

sobes.tech AI

Answer from AI

In the first example with a numeric list:

var list = List.of(5, 13, 34);

list.stream()
    .map(x -> x % 10)        // Convert numbers to their last digit: 5, 3, 4
    .peek(System.out::println) // Print each last digit
    .filter(x -> x > 3)       // Filter only digits greater than 3: 5, 4
    .forEach(System.out::println); // Print the filtered digits

Output will be:

5
3
4
5
4

Explanation: peek outputs all last digits, while forEach outputs only those greater than 3.

In the second example with animals:

List<String> animals = List.of("dog", "cat", "parrot");
animals.stream()
    .sorted()               // Sort: cat, dog, parrot
    .peek(item -> System.out.println(item)) // Output sorted items
    .map(String::length);   // Convert to string length, but result is not used
System.out.println(animals);

Here, map does not invoke a terminal operation, so the stream does not execute, and peek outputs nothing. The final output will be the original list [dog, cat, parrot].

To fix this, you need to add a terminal operation, such as collect or forEach.

Key points:

  • peek is used for debugging, but without a terminal operation, the stream does not execute.
  • A terminal operation is necessary to run the stream processing.
  • map without a terminal operation does not trigger execution.

Example fix for the second code:

animals.stream()
    .sorted()
    .peek(System.out::println)
    .map(String::length)
    .forEach(len -> {}); // or collect(Collectors.toList())

This way, peek will output the sorted elements.

var list = List.of(5, 13, 34); list.stream() .map(x… - sobes.tech