Stream skip() method in Java with examples
Prerequisite : Streams in java
The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the encounter order and not just any n elements.
Note : If a stream contains less than N elements, then an empty stream is returned.
Stream<T> skip(long N) Where N is the number of elements to be skipped and this function returns new stream as output.
Exception : If the value of N is negative, then IllegalArgumentException is thrown by the function.
Example 1 : Implementation of skip function.
New stream is : 6 8 10 12 14 16
Difference between limit() and skip() :
- The limit() method returns a reduced stream of first N elements but skip() method returns a stream of remaining elements after skipping first N elements.
- limit() is a short-circuiting stateful intermediate operation i.e, when processed with an infinite input, it may produce a finite stream as a result without processing the entire input but skip() is a stateful intermediate operation i.e, it may need to process the entire input before producing a result.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.