This post will discuss how to get a slice of a stream in Java. In other words, we need to get a new stream of elements between two specified positions.

1. Skip elements

The idea is to call the skip(n) method to discard the first n elements of the specified stream and then use the limit(k) method to return a new stream consisting of the next k elements in the encounter order.

Download  Run Code

 
Please note that:

  1. Both skip() and limit() offer poor performance with parallel streams since consistency with the encounter order is required.
  2. The limit(fromIndex, toIndex) throws a java.lang.IllegalArgumentException if fromIndex is more than toIndex.
  3. If toIndex is more than the total number of elements in the stream, then a stream ranging from fromIndex till the last index is returned.
  4. If the stream has fewer elements than fromIndex, an empty stream is returned.
  5. If fromIndex is negative, skip(fromIndex) throws a java.lang.IndexOutOfBoundsException.

2. Get a Sublist

Here, the idea is to convert the stream to a list, use the sublist() method to get the sublist of elements between specified indexes, and finally convert it back to a stream.

Download  Run Code

 
This method also throws java.lang.IndexOutOfBoundsException if fromIndex is negative or toIndex is more than the stream’s size.

3. Using Collectors

This is similar to the first approach but uses collectors to first convert the stream to a list and then use a finisher method of a collector to get a sublist of desired elements and convert the sublist back to a stream.

Download  Run Code

That’s all about getting a slice of a Stream in Java.