Junior — Middle
Can you explain how the peek method is implemented in Java streams and what its main purpose is?
sobes.tech AI
Answer from AI
In Java, the peek method is used in the Stream API and is intended for intermediate operations that allow you to look at the elements of the stream without modifying the stream itself. Its main purpose is to perform side effects, such as logging or debugging, without affecting the further processing.
peek takes a Consumer — a function applied to each element of the stream, but does not modify it.
Example:
import java.util.stream.Stream;
public class PeekExample {
public static void main(String[] args) {
Stream.of("one", "two", "three")
.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. This is useful for debugging stream operation chains.