A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/stream-peek-method-in-java-with-examples/ below:

Stream peek() Method in Java with Examples

Stream peek() Method in Java with Examples

Last Updated : 05 May, 2024

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:

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 the 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 the Integers
        List<Integer> list
            = Arrays.asList(0, 2, 4, 6, 8, 10);
        // Using peek with the forEach() method
        // which is a terminal operation
        list.stream()
            .peek(System.out::println)
            .forEach(x -> {});
    }
}


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4