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 peek
is a non-terminal operation that allows you to perform an operation on each element of the stream without changing the contents of the stream.
peek
The syntax of the method is as follows:
Stream<T> peek(Consumer<? super T> action)
where action
is a function that receives an element and performs an operation.
peek
The 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 peek
simple 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 numbers
and then process each element through a stream. In the operation of the stream peek
, we print the value of each number. We then use map
an 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 peek
methods, 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 peek
the 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 peek
add a terminal operation after the method, such as collect
, forEach
etc.
To summarize, peek
a 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.