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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap