Close

Java 8 Streams - LongStream.peek Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.LongStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.LongStreamLongStreamLogicBig

Method:

LongStream peek(LongConsumer action)

This intermediate operation returns a LongStream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

Examples


package com.logicbig.example.longstream;

import java.util.stream.LongStream;

public class PeekExample {

public static void main(String... args) {
LongStream longStream = LongStream.range(1, 6);
longStream.peek((x) -> System.out.println("peek " + x))
.filter(lg -> lg % 2 == 0)
.forEach(System.out::println);
}
}

Output

peek 1
peek 2
2
peek 3
peek 4
4
peek 5




package com.logicbig.example.longstream;

public class PeekExample2 {

public static void main(String... args) {

}
}

Output





Parallel stream:

package com.logicbig.example.longstream;

import java.util.stream.LongStream;

public class PeekExample3 {

public static void main(String... args) {
LongStream longStream = LongStream.range(1, 6);
longStream.parallel()
.peek((x) -> System.out.println("peek " + x))
.filter(lg -> lg % 2 == 0)
.forEach(System.out::println);
}
}

Output

peek 3
peek 1
peek 2
peek 4
peek 5
2
4




See Also