Junior — Middle
What is the function of the peek method in the Stream API?
sobes.tech AI
Answer from AI
The peek method in the Stream API is used for intermediate inspection of stream elements without modifying the stream itself. It allows performing an action on each element (for example, printing to the screen or logging) without affecting further processing.
peek is useful for debugging or logging, as it does not alter the stream and does not trigger its processing (lazy evaluation).
Example of usage:
Stream.of("a", "b", "c")
.peek(s -> System.out.println("Processing: " + s))
.map(String::toUpperCase)
.forEach(System.out::println);
In this example, peek outputs each element before converting it to uppercase.