How to Get Slice of a Stream in Java

In this post, we will see how to get 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 skip(n) method to discard the first n elements of the specified stream and then use limit(k) method to return a new stream consisting of the next k elements in the encounter order.

 

Download   Run Code

Output:

2
3
4
5

 
Please note that:

1. Both skip() and limit() offers very 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 number of elements in the stream, then a stream ranging from fromIndex till the last index is returned.

4. If the stream has less number of elements than fromIndex, an empty stream is returned.

5. If fromIndex is negative, skip(fromIndex) throws a java.lang.IndexOutOfBoundsException.

 

2. Get a Sublist

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

 

Download   Run Code

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

 

3. Using Collectors:

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

 

Download   Run Code

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz