Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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:

  1. Use peek() in the middle of a stream pipeline to log or debug elements.
  2. It does not change the elements themselves β€” just inspects them.
  3. 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.