This intermediate operation returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
Using peek without any terminal operation does nothing.
package com.logicbig.example.stream;
import java.util.Arrays;
public class PeekExample {
public static void main(String... args) {
String[] array = {"one", "two", "three", "four"};
Arrays.stream(array).peek(System.out::println);
}
}
Output
Stream.peek(Consumer<? super T> action) performs the provided consumer action on each element. Other peek methods are: IntStream.peek(IntConsumer), LongStream.peek(LongConsumer) and DoubleStream.peek(DoubleConsumer action). This example demonstrates that peek operation doesn't call the consumer action in encounter order.
package com.logicbig.example;
import java.util.stream.IntStream;
public class PeekExample {
public static void main (String[] args) {
IntStream.range(0, 5).parallel().peek(System.out::println).
count();
}
}
Output
0
1
2
3
4
Original PostThe output is non-deterministic.
package com.logicbig.example;
import java.util.stream.IntStream;
public class SideEffectWithPeek {
public static void main (String[] args) {
IntStream.range(0, 5)
.unordered()
.parallel()
.map(x -> x * 2)
.peek(System.out::println)
.count();
}
}
Output
0
8
2
4
6
Original Post