Course contentsShow
← Java
Lesson 1456 of 2,87032. Streams API: Intermediate OperationsFree lesson

Basic peek Syntax and Usage

Learning the peek method signature and how to insert it into stream pipelines to observe elements.

Basic peek Syntax and Usage

You'll learn: How to use peek() to observe elements flowing through a stream pipeline without altering them.

The Core Idea

The peek() method is an intermediate operation that lets you perform an action on each element as it passes through, then returns a stream containing those same elements unchanged. Think of it as a window into your stream pipeline—you can look at what's flowing by, log it, debug it, or perform side effects, but the stream itself continues unmodified.

Imagine a factory conveyor belt with an inspector station. Workers can observe items passing by, take notes, or check quality without removing or changing the items. That's peek() in action.

The Method Signature

Stream<T> peek(Consumer<? super T> action)

The method takes a Consumer (a lambda that accepts an element and returns nothing) and returns a new stream with the same elements.

Basic Syntax Examples

Logging elements as they flow:

List<String> names = List.of("Alice", "Bob", "Charlie");

names.stream()
     .peek(name -> System.out.println("Processing: " + name))
     .filter(name -> name.length() > 3)
     .forEach(System.out::println);

Using method references:

Stream.of(1, 2, 3, 4)
      .peek(System.out::println)  // Prints each number
      .map(n -> n * 2)
      .forEach(System.out::println);

Multiple peek operations for debugging:

List.of("apple", "banana", "cherry")
    .stream()
    .peek(s -> System.out.println("Original: " + s))
    .filter(s -> s.startsWith("a"))
    .peek(s -> System.out.println("After filter: " + s))
    .forEach(s -> System.out.println("Final: " + s));

Key Takeaway: peek(Consumer<T>) is an intermediate operation that performs an action on each element while passing it through unchanged—perfect for debugging or observing stream pipelines in action.