The Java Stream peek() method is an intermediate operation.
The Java Stream peek() method takes a Consumer interface as a parameter. The Consumer will get called for each element in the stream. The peek() method returns a new Stream that contains all the elements in the original stream.
The purpose of the peek() method is, as the method says, to peek at the elements in the stream, not to transform them. Keep in mind that the peek method does not start the internal iteration of the elements in the stream. You need to call a terminal operation for that.
Java Stream peek() Example 1
Here is a Java Stream peek() example:
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args)
{
Stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("Mapped value: " + e))
.collect(Collectors.toList());
}
}
Output:
Filtered value: three
Mapped value: THREE
Filtered value: four
Mapped value: FOUR
Java Stream peek() Example 2
Java program to use peek() API to debug the Stream operations and log Stream elements as they are processed.import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> newList = list.stream()
.peek(System.out::println)
.collect(Collectors.toList());
System.out.println(newList);
}
}
Output:
1
2
3
4
5
[1, 2, 3, 4, 5]
Java Stream Methods/APIs Examples
- Java Stream filter() Example
- Java Stream map() Example
- Java Stream flatMap() Example
- Java Stream distinct() Example
- Java Stream limit() Example
- Java Stream peek() Example
- Java Stream anyMatch() Example
- Java Stream allMatch() Example
- Java Stream noneMatch() Example
- Java Stream collect() Example
- Java Stream count() Example
- Java Stream findAny() Example
- Java Stream findFirst() Example
- Java Stream forEach() Example
- Java Stream min() Example
- Java Stream max() Example
- Java Stream reduce() Example
- Java Stream toArray() Example