This post will discuss how to get a slice (or a sub-list) from a List in Java.

1. Using list.subList() method

You can use the List.sublist() method to get a view of the portion of this list between the specified range of indices.

Download  Run Code

Output:

[D, E, F]

 
Note that the sublist returned by the subList() method is backed by the original list, any non-structural changes in the sublist are reflected in the original list and vice-versa. If you want to avoid this behavior, it is advisable to wrap the list using the ArrayList constructor. For instance,

Download  Run Code

Output:

[D, E, F]

2. Using Stream API

The idea here is to get the stream of the elements in the list and call the skip(n) method to skip the first n elements. Then call the limit(k) method to return a new stream consisting of the next k elements in the encounter order and collect the stream to a new list.

This process generates the sublist of the original list in the range [n, n + k].

Download  Run Code

Output:

[D, E, F]

3. Using Enhanced For loop

Here’s a version without streams using an enhanced for loop (self-explanatory):

Download  Run Code

Output:

[D, E, F]

 
The code can be simplified using a regular for loop, as shown below:

Download  Run Code

Output:

[D, E, F]

That’s all about getting a slice from a List in Java.