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:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!