This post will discuss how to get a sublist of a list between two specified ranges in Kotlin.

1. Custom Routine

A naive solution is to add elements from the original list present between the specified range to the sublist.

Download Code

2. Using getSubList() function

You can also use the native subList() function that returns a view of the portion of the list between the specified range.

Download Code

 
Note that the list returned by subList() is backed by the original list. If the original list is structurally modified in any way, the behavior of the list is undefined, and ConcurrentModificationException may be thrown. For instance,

Download Code

 
The solution to this is to create a new MutableList instance from the returned view by subList(), as shown below:

Download Code

That’s all about getting a sublist of a list in Kotlin.