Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaStream peek() Method in Java with Examples

Stream peek() Method in Java with Examples

In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation, as it creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. 

Syntax: 

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

Here, Stream is an interface and T is the type of stream element. action is a non-interfering action to perform on the elements as they are consumed from the stream and the function returns the new stream.Now we need to understand the lifecycle of peek() method via its internal working via clean java programs listed below as follows:

Note:

  • This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.
  • Since Java 9, if the number of elements is known in advance and unchanged in the stream, the .peek () statement will not be executed due to performance optimization. It is possible to force its operation by a command (formal) changing the number of elements eg. .filter (x -> true).
  • Using peek without any terminal operation does nothing.

Example 1:

Java




// Java Program to Illustrate peek() Method
// of Stream class Without Terminal Operation Count
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating a list of Integers
        List<Integer> list
            = Arrays.asList(0, 2, 4, 6, 8, 10);
 
        // Using peek without any terminal
        // operation does nothing
        list.stream().peek(System.out::println);
    }
}


 
 

Output: 

 

 

From the above output, we can perceive that this piece of code will produce no output

 

Example 2:

 

Java




// Java Program to Illustrate peek() Method
// of Stream class With Terminal Operation Count
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating a list of Integers
        List<Integer> list
            = Arrays.asList(0, 2, 4, 6, 8, 10);
 
        // Using peek with count() method,Method
        // which is a terminal operation
        list.stream().peek(System.out::println).count();
    }
}


 
 

Output:  

 

0
2
4
6
8
10

 

RELATED ARTICLES

Most Popular

Recent Comments