What is the skip() method of the Stream Interface?

The skip(N) method will return a new stream that was created from an existing stream by truncating the first N elements.

Syntax

Stream<T> skip(long N)
  • N: The number of elements to be skipped.

  • If N is greater than the size of this stream, an empty stream is returned.

  • The skip method is a cheap operation on a sequential stream.

  • In the ordered parallel stream, the skip method may be expensive if the value of N is large. This is because the stream is processed in a parallel manner by different threads. This performance issue can be avoided by using the unordered stream, removing the ordering constraint with BaseStream.unordered(), or using a sequential stream instead of a parallel stream.

  • IllegalArgumentException is thrown if we pass negative numbers as value for N.

Example

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class SkipExample {
public static void main(String[] args)
{
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> newList = numbers
.skip(3)
.collect(Collectors.toList());
System.out.println(newList);
}
}

In the above code:

  • We created a Stream of integers with the name numbers and the values:
1,2,3,4,5,6,7,8,9,10
  • We called the skip(3) method on the numbers stream. The skip(3) method will return a new stream with all the elements of the numbers stream except the first three elements.

  • Using the collect(Collectors.toList()) method, we collected the stream as a List.