Iterate from second item of a List in Kotlin
This article explores different ways to iterate from the second item of a List in Kotlin.
1. Using subList() function
A simple solution is to use the subList() function to iterate through the sublist starting from the second element till the end of the list.
|
1 2 3 4 5 6 |
fun main() { val nums = listOf(1, 2, 3, 4, 5) for (i in nums.subList(1, nums.size)) { println(i) } } |
Output:
2
3
4
5
The subList() function just returns a “view” of the original list and does not create an intermediary list. Note that the starting index is inclusive, and the ending index is exclusive. Here’s an equivalent version using the forEach function:
|
1 2 3 4 |
fun main() { val nums = listOf(1, 2, 3, 4, 5) nums.subList(1, nums.size).forEach(::println) } |
Output:
2
3
4
5
2. Using drop() function
Alternatively, you can call the drop() function to discard the first element of the list, and process the remaining elements. This is demonstrated below:
|
1 2 3 4 |
fun main() { val nums = listOf(1, 2, 3, 4, 5) nums.drop(1).forEach(::println) } |
Output:
2
3
4
5
3. Using List Iterator
Another option to iterate over the elements in the list is to create a ListIterator starting from the second position of the list. For instance,
|
1 2 3 4 5 6 7 8 |
fun main() { val nums = listOf(1, 2, 3, 4, 5) val it = nums.listIterator(1) while (it.hasNext()) { println(it.next()) } } |
Output:
2
3
4
5
4. Using Ranges
Kotlin lets you easily create Integral type ranges, which can be iterated over. The idea is to create a range of list indices between the second element and the last, as shown below:
|
1 2 3 4 5 6 |
fun main() { val nums = listOf(1, 2, 3, 4, 5) for (i in 1 until nums.size) { println(nums[i]) } } |
Output:
2
3
4
5
Alternatively, you can use the operator form .. of ranges, with the lastIndex:
|
1 2 3 4 5 6 |
fun main() { val nums = listOf(1, 2, 3, 4, 5) for (i in 1..nums.lastIndex) { println(nums[i]) } } |
Output:
2
3
4
5
That’s all about iterating from the second item 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 :)