Skipping elements in parallel stream:
package com.logicbig.example.stream;
import java.util.stream.Stream;
public class SkipExample2 {
public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};
Stream.of(s)
.parallel()
.skip(2)
.forEach(System.out::println);
}
}
Output
four
three
Stream.skip(long n), IntStream.skip(long n), LongStream.skip(long n) and DoubleStream.skip(long n) methods discard the first n elements of the streams. This example shows the performance difference of skip operation between ordered parallel vs unordered parallel stream. For parallel stream, skip() method performs better, if the stream is unordered.
package com.logicbig.example;
import java.util.stream.IntStream;
public class SkipExample {
public static void main (String[] args) {
PerformanceTestUtil.runTest("unordered parallel skip", () -> {
IntStream intStream = IntStream.range(1, 100000000);
intStream.unordered().parallel().skip(1000).toArray();
});
PerformanceTestUtil.runTest("ordered parallel skip", () -> {
IntStream intStream = IntStream.range(1, 100000000);
intStream.parallel().skip(1000).toArray();
});
}
}
Output
unordered parallel skip time taken: 142.7 milliseconds
ordered parallel skip time taken: 151.5 milliseconds
Original Post