Open In App

IntStream skip() Method in Java

Last Updated : 07 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the IntStream skip(long n) method returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains less than n elements, then an empty stream will be returned.

Note: IntStream skip() is a stateful intermediate operation, i.e, it may incorporate state from previously seen elements when processing new elements.

Syntax of IntStream skip() Method

IntStream skip(long n)

  • Parameter: n: This is the number of leading elements to discard. It must be non-negative.
  • Return value: It returns a new IntStream with the first n elements removed.
  • Exception: If n is negative, it throws an IllegalArgumentException.

Important Points:

  • skip() is stateful, and it needs to count elements before emitting the remaining.
  • The elements maintain their encounter order after skipping.
  • If n >= stream length, the returned stream is empty.
  • It works with parallel streams, but results may not be in the original order.

Examples of Java IntStream skip() Method

Example 1: Skipping Elements in a Sequential Stream

Java
// Java program to skip first 4 elements in IntStream.range
import java.util.stream.IntStream;

public class Geeks {
    public static void main(String[] args) {
        
        // Create an IntStream of numbers
        IntStream s = IntStream.range(2, 10);

        // Skip the first 4 elements and print the rest
        s.skip(4)
              .forEach(System.out::println);
    }
}

Output
6
7
8
9

Explanation: In this example, it skips the numbers 2, 3, 4, 5 and the rest numbers are printed.


Example 2: Skipping in a Parallel Stream

Java
// Java program to skip elements in a parallel IntStream
import java.util.stream.IntStream;

public class Geeks {
    public static void main(String[] args) {
        
        // Create an IntStream of numbers
        IntStream s = IntStream.range(2, 10);

        // Convert to parallel 
        // skip first 4, then print
        s.parallel()
              .skip(4)
              .forEach(System.out::println);
    }
}

Output
8
9
6
7

Note: In a parallel stream, the order may vary if we use forEachOrdered() on an ordered stream.

When to Use skip()

  • It skip a fixed number of records, for example, pagination.
  • Chain with other operations like limit(), filter(), etc.

Example of skip() and limit()

Java
// Java program combining skip() and limit()
import java.util.stream.IntStream;

public class Geeks {
    
    public static void main(String[] args) {
        
        // Create an infinite IntStream
        // skip 10, then take next 5
        IntStream.iterate(1, i -> i + 1)
                 .skip(10)
                 .limit(5)
                 .forEach(System.out::println);
    }
}

Output
11
12
13
14
15

Next Article
Practice Tags :

Similar Reads