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
Nis greater than the size of this stream, an empty stream is returned. -
The
skipmethod is a cheap operation on a sequential stream. -
In the ordered parallel stream, the
skipmethod may be expensive if the value ofNis 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 withBaseStream.unordered(), or using a sequential stream instead of a parallel stream. -
IllegalArgumentExceptionis thrown if we pass negative numbers as value forN.
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
Streamof integers with the namenumbersand the values:
1,2,3,4,5,6,7,8,9,10
-
We called the
skip(3)method on thenumbersstream. Theskip(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 aList.