Java 8 FAQ: Top Questions
19. What is the purpose of the peek() method in Java 8 Streams?
The peek() method is an intermediate operation that allows performing a side-effect on each element in a stream as it passes through the pipeline. It's primarily used for debugging and inspecting stream content without modifying it.
πΊοΈ Step-by-Step Instructions:
- Use
peek()in the middle of a stream pipeline to log or debug elements. - It does not change the elements themselves β just inspects them.
- Since it's lazy,
peek()requires a terminal operation to trigger execution.
π₯ Example Input:
List words = Arrays.asList("apple", "banana", "cherry");
List result = words.stream()
.peek(w -> System.out.println("Peeked: " + w))
.map(String::toUpperCase)
.collect(Collectors.toList());
π Expected Output:
Peeked: apple
Peeked: banana
Peeked: cherry
[APPLE, BANANA, CHERRY]
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class PeekExample {
public static void main(String[] args) {
List words = Arrays.asList("apple", "banana", "cherry");
List result = words.stream()
.peek(w -> System.out.println("Peeked: " + w))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result);
}
}
π Detailed Explanation:
- peek(): Used for intermediate side-effects without changing the data.
- Helpful for logging, tracing, or debugging stream operations.
- Can be misused for side-effecting logic; not recommended in production logic flows.
π οΈ Use Cases:
- Debugging transformation pipelines during development.
- Logging intermediate states in complex stream flows.
- Monitoring data progression without affecting results.
