Java 8 Stream peek method Example
7 years ago Lalit Bhagtani 0
In this tutorial, we will learn about Java 8 stream peek method.
peek() method :-
This method takes one Consumer as an argument, this consumer accepts one parameter T as an input argument and return one stream of parameter T as a return value. The main purpose of this method is to support debugging, When you want to see ( peek ) the elements as they flow through the certain point in a stream pipeline. You can achieve this by using a Consumer Interface with System.out.println in it.
Syntax :- Stream<T> peek ( Consumer<? super T> action )
Reference :- peek() method JavaDocs
Problem Statement :-
You have given a list of integers first, find all the integers which are greater than 5 and then all the integers which are smaller than 9. Print all the values on the system console during first filter operation for debugging purpose.
Java 7 :- Implementation in Java 7.
public static void main(String[] args){ List<Integer> filterList = new ArrayList<Integer>(); List<Integer> numList = Arrays.asList(1,3,4,5,2,7,9); for(Integer num:numList){ if(num >= 5){ filterList.add(num); System.out.println("Filtered Value : "+num); } } List<Integer> finalList = new ArrayList<Integer>(); for(Integer num:filterList){ if(num < 9){ finalList.add(num); } } System.out.println(finalList); }
Java 8 Stream peek :- Implementation using stream API.
public static void main(String[] args) { List<Integer> numList = Arrays.asList(1,3,4,5,2,7,9); List<Integer> filterList = numList.stream().filter(e -> e >= 5) .peek(e -> System.out.println("Filtered value: " + e)) .filter(e -> e < 9) .collect(Collectors.toList()); System.out.println(filterList); }
Result :-
Filtered Value : 5 Filtered Value : 7 Filtered Value : 9 [5, 7]
That’s all for Java 8 Stream peek method. If you liked it, please share your thoughts in comments section and share it with others too.