Get a sublist of a list in Kotlin
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun <T> getSubList(list: List<T>, start: Int, end: Int): List<T>? { val subList: MutableList<T> = ArrayList() for (i in start..end) { subList.add(list[i]) } return subList } fun main() { val list = mutableListOf("A", "B", "C", "D", "E") val subList = getSubList(list, 2, 3) println(subList) // [C, D] } |
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.
1 2 3 4 5 6 7 8 9 10 |
fun <T> getSubList(list: List<T>, start: Int, end: Int): List<T>? { return list.subList(start, end + 1) } fun main() { val list = mutableListOf("A", "B", "C", "D", "E") val subList = getSubList(list, 2, 3) println(subList) // [C, D] } |
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,
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> getSubList(list: MutableList<T>, start: Int, end: Int): List<T> { val subList: List<T> = list.subList(start, end + 1) list.removeAt(2) // lead to `java.util.ConcurrentModificationException` return subList } fun main() { val list = mutableListOf("A", "B", "C", "D", "E") val subList = getSubList(list, 2, 3) println(subList) // [C, D] } |
The solution to this is to create a new MutableList
instance from the returned view by subList()
, as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> getSubList(list: MutableList<T>, start: Int, end: Int): List<T>? { val subList: MutableList<T> = ArrayList(list.subList(start, end + 1)) list.removeAt(2) // ConcurrentModificationException not thrown return subList } fun main() { val list = mutableListOf("A", "B", "C", "D", "E") val subList = getSubList(list, 2, 3) println(subList) // [C, D] } |
That’s all about getting a sublist of a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)