Junior — Middle
What is the role of the peek method in Java's Stream API functional streams?
sobes.tech AI
Answer from AI
The peek method in Java's Stream API is used for intermediate inspection of stream elements without modifying the stream itself. It is useful for debugging or performing side actions such as logging.
For example:
Stream.of("one", "two", "three")
.peek(s -> System.out.println("Processing: " + s))
.map(String::toUpperCase)
.forEach(System.out::println);
Here, peek outputs each element before transformation, without affecting the stream's result.