In this article, we will discuss Stream’s peek() method in details with examples
1. Stream peek() method :
- This Stream method is an intermediate operation which reads given stream applying provided Consumer action on each elements, as they pass through the Stream
- Stream.peek() method does nothing until a terminal operation is executed on the Stream
- Stream’s peek() method is stateless which means it is non-interfering with other elements in the stream
- For parallel stream pipelines, the action may be called at whatever time and in whatever thread the element is made available by the upstream operation
- If the action modifies shared state, it is responsible for providing the required synchronization
- API Note :- This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline
- Method signature :- Stream<T> peek(Consumer<? super T> action)
2. Stream peek() method examples :
2.1 Stream.peek() does nothing
- A list contains integers numbers
- We are applying peek() method to sneak through Stream elements to print to the console
- But nothing gets printed to the console because an intermediate operation doesn’t get executed until a terminal operation is executed
- Here, we don’t have a terminal operation
package net.bench.resources.stream.peek.example;
import java.util.Arrays;
import java.util.List;
public class StreamPeekMethod {
public static void main(String[] args) {
// list of integer numbers
List<Integer> numbers = Arrays.asList(
1,2,3,4,5,6,7
);
// Stream.peek()
numbers // data source
.stream() // get Stream
.peek(System.out::println); // intermediate operation
}
}
Output:
2.2 Stream.peek() with terminal operation
- A list contains integers numbers
- We are applying peek() method to sneak through Stream elements to print to the console
- Here, all integers numbers with duplicates gets printed to console because of terminal operation collect()
- collect() method collects elements and store it into Set thereby removing duplicates in the unordered/random fashion
package net.bench.resources.stream.peek.example;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class StreamPeekMethodWithTerminalOp {
public static void main(String[] args) {
// list of integer numbers
List<Integer> numbers = Arrays.asList(
1,
2,2,
5,5,5,
7,7,7
);
// Stream.peek()
System.out.println("Stream.peek() result :- ");
Set<Integer> uniqueNumbers =
numbers // data source
.stream() // get Stream
.peek(System.out::println) // intermediate Op
.collect(Collectors.toSet()) // terminal Op
;
// print to console
System.out.println("\nPrinting Unique numbers :- ");
uniqueNumbers.forEach(num -> System.out.print(" " + num));
}
}
Output:
Stream.peek() result :-
1
2
2
5
5
5
7
7
7
Printing Unique numbers :-
1 2 5 7
2.3 Stream.peek() with filter() and map() methods
- A list contains String elements
- First, we are filtering all String elements whose length is greater than 3 and then invoking peek() method to print the value to the console
- Secondly, we are applying map() method to the already filtered values to map String elements to Upper Case and then invoking peek() method to print the value to the console
- Finally, all filtered and upper case mapped String elements are collected into List using a terminal operation method collect()
- This list is iterated/printed to the console using forEach() method
package net.bench.resources.stream.peek.example;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamPeekFilterMapMethod {
public static void main(String[] args) {
// order -> filter, peek, map, peek
System.out.println("Filtering (str.length>3) and Mapping (str.UpperCase) :- \n");
List<String> numbers =
Stream.of("one", "two", "three", "four") // data source
.filter(e -> e.length() > 3) // filter
.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase) // map
.peek(e -> System.out.println("Mapped value: " + e))
.collect(Collectors.toList()); // terminal operation
// print to console
System.out.println("\n\nAfter filtering and mapping to UpperCase :- ");
numbers.stream().forEach(System.out::println);
}
}
Output:
Filtering (str.length>3) and Mapping (str.UpperCase) :-
Filtered value: three
Mapped value: THREE
Filtered value: four
Mapped value: FOUR
After filtering and mapping to UpperCase :-
THREE
FOUR
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
Happy Coding !!
Happy Learning !!