Junior — Middle
Can you explain how the peek() method works in Java Stream API and in what situations it is used?
sobes.tech AI
Answer from AI
The peek() method in Java Stream API is used for intermediate inspection of stream elements without modifying the stream itself. It accepts a Consumer — a function that performs some action on each element, such as logging or debugging.
Important: peek() does not modify the elements and is not a terminal operation, so the stream must be 'started' with a terminal operation (e.g., collect(), forEach()).
Example usage:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
List<String> filtered = names.stream()
.filter(name -> name.length() > 3)
.peek(name -> System.out.println("Filtered value: " + name))
.collect(Collectors.toList());
Here, peek() outputs the filtered names for debugging without affecting the result.
peek() is typically used for:
- Debugging stream chains
- Logging intermediate values
- Performing side effects without changing data
However, peek() should not be used to change state or data, as this contradicts functional style and can lead to unpredictable results.