Table of Contents
Stream peek() in Java 8
What have we learned so far
1. Functional Interface And Default Methods In Java 8 –
PART 1 : FUNCTIONAL INTERFACE AND DEFAULT METHODS IN JAVA 8
2. Lambda Expression in Java 8
PART 2 – LAMBDA EXPRESSION IN JAVA 8
3. Method Reference in Java 8
PART 3 – METHOD REFERENCE IN JAVA 8
4. Optional in Java 8
PART 4 – OPTIONAL IN JAVA 8
5. filter(), findAny() in Java 8
PART 5 – FILTER(), FINDANY() IN JAVA 8
6. map() vs flatMap() in Java 8
PART 6 – MAP() VS FLATMAP() IN JAVA 8
How Stream.peek() method is different from other methods?
What is the use of peek() method in Java 8?
Stream<T> peek(Consumer<? super T> action);
Here :
action: is a consumer object which takes the piece of code to execute in peek()
Returns the exact stream to the next pipeline operation.
Stream.peek() is an Intermediate method, which will return the same Stream passed to it.
Let’s take an example to understand more on it. Suppose we want to log the all processing Student objects and objects which got passed during filter(). Then we can use peek() method before and after filter() method to log the Student name.
private static void peek(List<Student> students) { System.out.println("######## Executing peek() :######## "); students.stream() .peek(stud -> {System.out.println("Processing Student Name : "+ stud.getName());}) .filter(student -> "Mumbai".equals(student.getCity())) .peek(stud -> { System.out.println("Filtered Student Name :" + stud.getName());}) .forEach(System.out::println); System.out.println("######## Ending the execution of peek() ######## "); }
Output
######## Executing peek() :########
Processing Student Name : Saurabh
Processing Student Name : Robert
Processing Student Name : John
Filtered Student Name :John
Student [name=John, city=Mumbai, age=21]
Processing Student Name : Roman
Processing Student Name : Randy
Filtered Student Name :Randy
Student [name=Randy, city=Mumbai, age=17]
######## Ending the execution of peek() ########
Source Code
Download source code of Java 8 features from below git repository :
java-8-features
Java 8 Features Tutorial
https://www.onlyfullstack.com/java-8-features-tutorial/
Lets go to our next tutorial where we will discuss
In this tutorial we will understand below topics
– Different Short circuiting operations in Java 8
– limit() in Java 8
– findFirst(), findAny() in Java 8
– allMatch() anyMatch() noneMatch() in Java 8