September 4, 2021

Java Stream skip() Method With Examples

The skip(long n) method in the Java Stream API skips the first n element of the stream and returns a new stream consisting of the remaining elements of this stream.

skip method in Java Stream

Syntax of the method is as given below.

Stream<T> skip(long n)

Here n is the number of leading elements to skip. If you pass n as negative then IllegalArgumentException is thrown.

Points about skip method

  1. It is a stateful intermediate operation which means it will return a new Stream.
  2. If number of elements to skip (n) is greater than the elements contained in the Stream then an empty stream will be returned.
  3. skip(n) is constrained to skip not just any n elements, but the first n elements in the encounter order.
  4. skip() is generally a cheap operation on sequential stream pipelines.
  5. skip() can be quite expensive on ordered parallel pipelines, if n is a fairly large values, because of the constraint to skip first n elements in the encounter order.

skip() Java Example

Here we’ll try to get a sublist from a List using skip method. Method getSubListBySkipping() is a generic method that can work with any type of List, second argument passed to the method is the number of elements to be skipped. Results of the stream returned by skip() method are collected to a list and that new list is returned.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SkipDemo {

  public static void main(String[] args) {
    SkipDemo sd = new SkipDemo();
    // Used with list of Strings
    List<String> cityList = Arrays.asList("Delhi", "Mumbai", "London", "New York","Bengaluru");
    List<String> newList = sd.getSubListBySkipping(cityList, 3);
    System.out.println("List after skipping elements- " + newList);
    // Used with list of Integers
    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    List<Integer> tempList = sd.getSubListBySkipping(numList, 7);
    System.out.println("List after skipping elements- " + tempList);
  }

  // This method uses skip method to skip n elements
  public <T> List<T> getSubListBySkipping(List<T> originalList, long n){
    return originalList.stream().skip(n).collect(Collectors.toList());
  }
}
Output
List after skipping elements- [New York, Bengaluru]
List after skipping elements- [8, 9, 10]
That's all for the topic Java Stream skip() Method With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like

No comments:

Post a Comment