Sobes.tech
Junior — Middle

What is the role of the peek method in Stream API and in what cases is it used?

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 operation (such as logging or debugging) on each element passing through the stream without affecting the result.

peek accepts a Consumer and returns a new Stream, so it can be inserted into a chain of calls to observe the elements.

Example of usage:

List<String> list = Arrays.asList("one", "two", "three");
list.stream()
    .filter(s -> s.length() > 3)
    .peek(s -> System.out.println("Filtered value: " + s))
    .map(String::toUpperCase)
    .forEach(System.out::println);

In this example, peek outputs the filtered values before transformation.

The main use of peek is for debugging and logging intermediate results in a Stream chain without altering the stream.

What is the role of the peek method in Stream API and… - sobes.tech