SoFunction
Updated on 2025-04-12

Detailed explanation of peek method of Stream stream in Java and common usage scenarios

Preface

Java 8 has been introducedStreamAPI greatly simplifies collection operations, allowing developers to use streaming methods to perform data processing. Stream provides a series of very powerful operating methods, one of which ispeek()method.peek()is an intermediate operation that can be used to view the processing status of elements during the operation flow. This article will introduce in detailpeek()The usage scenarios and principles of the method, and the code examples help you understand in-depth.

1. Introduction to peek() method

peek()The method is defined inIn the interface, its signature is as follows:

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

effect:

peek()It's oneIntermediate operation, which allows us to perform an operation on each element of the stream, but does not change the elements in the stream or interrupt the processing of the stream. Commonly used as a debugging tool to view data in the stream in various operation steps. It receives aConsumerFunctions as parameters,ConsumerFunctions can perform certain actions on elements in each stream.

Features:

  • peek()It will not consume streams, it will just perform a bypass behavior.
  • Because it is an intermediate operation, it will not trigger the terminal operation, so after the call is completedpeek()After that, you need to call such asforEach()collect()This type of terminal operation triggers the processing of the flow.

Sample code:

import ;
import ;
import ;

public class PeekExample {
    public static void main(String[] args) {
        List&lt;Integer&gt; numbers = (1, 2, 3, 4, 5);

        // Use the peek method to debug the flow operation process        List&lt;Integer&gt; result = ()
                .filter(n -&gt; n % 2 == 0)  // Filter out even numbers                .peek(n -&gt; ("Filtered: " + n))  // View filter results                .map(n -&gt; n * n)  // Square even numbers                .peek(n -&gt; ("Mapped: " + n))  // View the mapping results                .collect(());  // Collect results
        ("The final result: " + result);
    }
}

Output result:

Filtered: 2
Mapped: 4
Filtered: 4
Mapped: 16
Final results: [4, 16]

In the example above,peek()Used to view the processing of elements in the stream, showing the processfilter()andmap()The data changes after operation.

2. Common usage scenarios of peek() method

2.1 Debug flow operation

peek()One of the main uses isdebug. When we deal with complex stream operation chains, it may be difficult to understand the effect of each intermediate operation. At this time, you can passpeek()To view the changes in the data in the stream after each operation, in order to find the problem or verify that the logic is correct.

import ;
import ;

public class DebugWithPeek {
    public static void main(String[] args) {
        List<String> words = ("apple", "banana", "cherry", "date");

        ()
                .filter(w -> () > 4)
                .peek(w -> ("Filtered: " + w))
                .map(String::toUpperCase)
                .peek(w -> ("Mapped to upper case: " + w))
                .forEach(::println);
    }
}

Output result:

Filtered: apple
Mapped to upper case: APPLE
Filtered: banana
Mapped to upper case: BANANA
Filtered: cherry
Mapped to upper case: CHERRY
APPLE
BANANA
CHERRY

You can see,peek()Methods are used for debugging so that we can seefilter()andmap()A string after operation.

2.2 Logging

In practical applications,peek()It can also be used to record the execution process of stream operations, such as writing the processing results of each element in the stream to the log. This is especially useful when the data processing chain is long.

import ;
import ;
import ;

public class LogWithPeek {
    private static final Logger logger = (());

    public static void main(String[] args) {
        List<Integer> numbers = (10, 20, 30, 40, 50);

        ()
                .filter(n -> n > 20)
                .peek(n -> ("After filter: " + n))
                .map(n -> n / 2)
                .peek(n -> ("After map: " + n))
                .forEach(::println);
    }
}

In this example,peek()Used to record logs, throughLoggerofinfo()Method records the processing status of each element in the stream.

2.3 Data inspection and verification

peek()It can also be used to perform data in the streamCheck and Verification. When you want to confirm whether the data in the stream complies with some rules but do not want to interrupt the processing of the stream,peek()It is a very good choice.

import ;
import ;

public class DataValidationWithPeek {
    public static void main(String[] args) {
        List&lt;String&gt; names = ("Alice", "Bob", "Charlie", "David");

        ()
                .filter(name -&gt; () &gt; 3)
                .peek(name -&gt; {
                    if (("C")) {
                        ("Note! The name begins with C: " + name);
                    }
                })
                .forEach(::println);
    }
}

In this example,peek()Method is used to check whether the name is letteredCStart without affecting other operations of the stream.

3. The difference from forEach()

peek()andforEach()It seems similar, and is used to operate on elements in a stream, but there are obvious differences:

  • peek()yesIntermediate operation,andforEach()yesTerminal operation
  • peek()Usually used for debugging or data checking, because it does not interrupt the chain operation of the stream; andforEach()It is an element used to final consumption stream.

Sample code:

import ;
import ;

public class PeekVsForEach {
    public static void main(String[] args) {
        List&lt;Integer&gt; numbers = (1, 2, 3, 4, 5);

        // Use peek() as an intermediate operation        ()
                .peek(n -&gt; ("Peeked: " + n))
                .map(n -&gt; n * 2)
                .forEach(::println);

        ("--------");

        // Use forEach() as terminal operation        ()
                .map(n -&gt; n * 2)
                .forEach(n -&gt; ("ForEach: " + n));
    }
}

Output result:

Peeked: 1
2
Peeked: 2
4
Peeked: 3
6
Peeked: 4
8
Peeked: 5
10
--------
ForEach: 2
ForEach: 4
ForEach: 6
ForEach: 8
ForEach: 10

You can see,peek()Used to view each element in a stream operation, andforEach()Used for final consumption elements.

4. Things to note

  • Lazy evaluationpeek()It is an intermediate operation, lazy, and only operates in the terminal (such asforEach()collect()The process of the stream will be executed only when the ) is called.

  • Not available for modifying stream elementspeek()Elements in the stream cannot be modified, it is only used to perform side-effect operations. If you need to modify the value of an element, you should usemap()method.

  • Applicable scenariospeek()The most suitable intermediate state for debugging or monitoring flows should not be abused, otherwise it may lead to reduced code readability.

5. Summary

In JavaStreamIn the API,peek()Method is a powerful tool that allows us to observe and debug data in the processing of streams, especially when the data processing chain is relatively long, it can help us track the state and changes of elements in the stream. But it should be noted thatpeek()Elements that cannot be used to modify streams are more used as means of debugging, logging and data checking.

Through rich code examples, we understandpeek()Common usage scenarios and precautions. In actual development, use it reasonablypeek()It can greatly help us debug and monitor flow operations. I hope this article can help you understand and master it in depth.peek()Use of

This is the article about the detailed explanation of the peek method of Stream stream in Java and common usage scenarios. For more information about peek method of Stream streams, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!