Java 8 Stream - limit() and skip() methods example

Posted on April 3, 2017


The limit(long n) method of java.util.stream.Stream object returns a reduced stream of first n elements. This method will throw an exception if n is negative.

The skip(long n) method of java.util.stream.Stream object returns a stream of remaining elements after skipping first n elements. This method will throw an exception if n is negative.

The following example demonstrates the use of the limit() and skip() methods.

StreamLimitSkipExample.java

package com.boraji.tutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author imssbora
 */
public class StreamLimitSkipExample {
   public static void main(String[] args) {
      
      List<Integer> numbers = new ArrayList<>();
      numbers.add(1);
      numbers.add(2);
      numbers.add(3);
      numbers.add(4);
      numbers.add(5);
      numbers.add(6);

      Stream<Integer> stream1 = numbers.stream();
      // Limit - return new stream of 3 elements
      System.out.println("--------Stream elements after limiting----------");
      stream1.limit(3).forEach((a) -> {
         System.out.println(a);
      });

      Stream<Integer> stream2 = numbers.stream();
      // Skip - return new stream of remaining elements
      // after skipping first 2 elements
      System.out.println("--------Stream elements after skipping----------");
      stream2.skip(2).forEach((a) -> {
         System.out.println(a);
      });
   }
}

Output

--------Stream elements after limiting----------
1
2
3
--------Stream elements after skipping----------
3
4
5
6