Java Stream skip() Method Tutorial

In this section, we will learn what the Stream skip() method is and how to use it in Java.

What is Java Stream skip() Method?

The Java Stream skip() method is used to skip n number of elements from a stream object.

For example, let’s say you have a stream that has 100 elements. But we want to skip the first incoming 30 elements from the stream and work with the rest of 70 elements.

This is where we can use the skip() method.

Note: this method is intermediate and lazy.

Java skip() Method Syntax:

Stream<T> skip(long n)

skip() Method Parameters:

The method takes one argument which is of type long and that is the first n number of elements we want to skip from the incoming stream.

skip() Method Return Value:

The return value of this method is a new stream that skipped n number of elements (equal to the argument of the method).

skip() Method Exceptions:

IllegalArgumentException: We get this exception if the argument of the method is a negative value.

Example: using Stream skip() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,7,86,54,5);
        stream.skip(10).forEach(e->System.out.print(e+", "));
    }
}

Output:

3, 23, 4, 23, 423, 2, 34, 56, 7, 86, 54, 5,

As you can see, the first 10 elements of this stream are now gone and we’ve printed the rest of elements after that.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies