Close

Java 8 Streams - Stream.skip Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

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

Method:

Stream<T> skip(long n)

This stateful intermediate operation returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned.


Examples


package com.logicbig.example.stream;

import java.util.stream.Stream;

public class SkipExample {

public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};

Stream.of(s)
.skip(2)
.forEach(System.out::println);
}
}

Output

three
four




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




See Also