Detailed explanation of peek usage in Java stream

In Java, Stream is a powerful tool for processing collection data. It provides a functional programming way to operate and transform data. A method in a Stream peekis a non-terminal operation that allows you to perform an operation on each element of the stream without changing the contents of the stream.

peekThe syntax of the method is as follows:

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

where actionis a function that receives an element and performs an operation.

peekThe main function of the method is to perform an operation on each element of the stream, such as printing the value of the element, logging, debugging, etc. It is typically used for debugging and observing the intermediate state of a stream without modifying the contents of the stream.

Here's a peeksimple example of how to use it:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> doubledNumbers = numbers.stream()
    .peek(n -> System.out.println("Processing number: " + n))
    .map(n -> n * 2)
    .collect(Collectors.toList());

In the above example, we create a list of integers numbersand then process each element through a stream. In the operation of the stream peek, we print the value of each number. We then use mapan operation to multiply each number by 2 and collect the results into a new list.

When we run the above code, we see the following output:

Processing number: 1
Processing number: 2
Processing number: 3
Processing number: 4
Processing number: 5

By using peekmethods, we can observe the processing of each element in the stream. This is useful for debugging and understanding the intermediate states of a stream.

It should be noted that peekthe method is an intermediate operation and does not trigger the terminal operation of the stream. If you want to modify the content of the stream or obtain the final result, you need to peekadd a terminal operation after the method, such as collect, forEachetc.

To summarize, peeka method is a non-terminal operation that performs an operation on each element of the stream. It is typically used for debugging and observing the intermediate state of a stream without modifying the contents of the stream.

Guess you like

Origin blog.csdn.net/kkwyting/article/details/133494638