Middle
What does the peek method do in Stream API?
sobes.tech AI
Answer from AI
The peek method in Java Stream API is designed to perform some action on each element of the stream without consuming it, that is, without modifying the stream itself. It returns the same stream, allowing for debugging or logging actions during processing.
Example usage:
// Example of using peek for logging
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> processedNames = names.stream()
.filter(name -> name.length() > 3) // Filter names longer than 3 characters
.peek(name -> System.out.println("Processing name: " + name)) // Log each name after filtering
.map(String::toUpperCase) // Convert to uppercase
.collect(Collectors.toList()); // Collect into a list
// Output:
// Processing name: Alice
// Processing name: Charlie
Important points:
peekis an intermediate operation.- It is mainly used for debugging or performing side effects.
- Do not rely on
peekto change the state of stream elements or external variables, as the order and number of calls can be unpredictable in parallel streams. - If no terminal operation follows
peek, the action specified inpeekwill not be executed.