In the following steps, we will learn to skip the first n entries of a Kotlin list:
- First, let's see how to drop the first n items in a collection. We will be using a list, but it also works with an array. Also, we will be using kotlin.stdlib, which contains the functions required in this recipe. The function to use here is drop:
fun main(args: Array<String>) {
val list= listOf<Int>(1,2,3,4,5,6,7,8,9)
var droppedList=list.drop(2)
droppedList.forEach {
print(" ${it} ")
}
}
//Output: 3 4 5 6 7 8 9
- To skip the last n items in the collection, you need to use the dropLast function:
fun main(args: Array<String>) {
val list= listOf<Int>(1,2,3,4,5,6,7,8,9)
var droppedList=list.dropLast(2)
droppedList.forEach {
print(" ${it} ")
}
}
//Output: 1 2 3 4 5 6 7
- This lambda function drops the item while the predicate returns true:
val list= listOf<Int>(1,2,3,4,5,6,7,8,9,1,2,3)
val droppedList=list.dropWhile { it<3 }
droppedList.forEach {
print(" ${it} ")
}
//Output: 3 4 5 6 7 8 9 1 2 3
- This function drops the items at the end while the condition is satisfied.
fun main(args: Array<String>) {
val list= listOf<Int>(1,2,3,4,5,6,7,8,9,3,1,2)
val droppedList=list.dropLastWhile { it<3 }
droppedList.forEach {
print(" ${it} ")
}
}
//Output: 1 2 3 4 5 6 7 8 9 3