Java 8 Stream API peek() method with Example

What is the peek() method in Java Stream API?

    The peek() method in Java 8 Stream API is an intermediate operation. We can perform an action on each element of the stream without modifying the elements.


What is the use of peek() method in Java Stream API?

    It peak() method is usually used for debugging or logging purposes.

    The peek() method takes a Consumer as an argument, and the provided consumer is applied to each element in the stream.


Examples of peak()

import java.util.Arrays;
import java.util.List;

public class PeekExample {

    public static void main(String[] args) {
        List<String> namesList = Arrays.asList("Mike","Sam","Alan");

        List<String> result = namesList.stream()
                .peek(name -> System.out.println("Original name: " + name))
                .map(name -> name.toUpperCase())
                .peek(uppercasedName -> System.out.println("Uppercase name: " + uppercasedName))
                .map(name -> "Hello " + name)
                .peek(nameWithGreeting -> System.out.println("Name with Greeting" + nameWithGreeting))
                .toList();
    }
}
Output:



Original name: Mike
Uppercase name: MIKE
Name with Greeting: Hello MIKE
Original name: Sam
Uppercase name: SAM
Name with Greeting: Hello SAM
Original name: Alan
Uppercase name: ALAN
Name with Greeting: Hello ALAN

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!