Streams – limit() and skip() operations

Stream limit() and skip() are intermediate operations in Java. 

The limit(n) method will limit the n numbers of elements to be processed in a stream.
The skip(n) method will skip the first n number from the stream.


Syntax of the limit() method

  Stream<T> limit(long maxSize)

The limit() method returns a new stream, a subset of the input stream truncated to be no longer than maxSize in length.


Syntax of the skip() method

  Stream<T> skip(long n)

The skip() method returns a stream consisting of the remaining elements after discarding the first n elements. If this stream contains fewer than n elements, we’ll get an empty stream.


Java Stream limit() and skip() operations – examples

Example 1
A program that takes a stream of integers and processes only the first 5 elements using the limit() method:

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

    List<Integer> resultList = numbers.stream()
            .limit(5)
            .map(num -> num * 2)
            .collect(Collectors.toList());

    System.out.println(resultList);
  }
}

Output: [2, 4, 6, 8, 10]


Example 2
A program that takes a stream of integers and multiplies elements by 2 but skips the first 5 elements, using the skip() method:

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

    List<Integer> resultList = numbers.stream()
            .skip(5)
            .map(num -> num * 2)
            .collect(Collectors.toList());

    System.out.println(resultList);
  }
}

Output: [12, 14, 16, 18, 20]


That’s it!

 

Leave a Reply

Your email address will not be published.