Close

Java 8 Streams - Stream.peek Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

Stream<T> peek(Consumer<? super T> action)

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.


Examples


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





package com.logicbig.example.stream;

import java.util.Arrays;

public class PeekExample2 {

public static void main(String... args) {
String[] array = {"one", "two", "three", "four"};
Arrays.stream(array).peek(System.out::println).count();
}
}

Output

one
two
three
four




parallel stream.

package com.logicbig.example.stream;

import java.util.Arrays;

public class PeekExample3 {

public static void main(String... args) {
String[] array = {"one", "two", "three", "four"};
Arrays.stream(array).parallel()
.peek(System.out::println).count();
}
}

Output

three
four
two
one




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 Post

The 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




See Also