How to use limit in Kotlin list
In this recipe, we will learn how to take specific items from the list. We will use the kotlin.stdlib
library for this purpose.
Getting ready
I'll be using IntelliJ IDEA for writing and running Kotlin code; you are free to use any IDE that can do the same task.
How to do it…
We will be using the take
function and its variants for limiting the items in the list.
take(n)
: Returns a list of the first n items:
fun main(args: Array<String>) {
val list= listOf(1,2,3,4,5)
val limitedList=list.take(3)
println(limitedList)
}
//Output: [1,2,3]
takeLast(n)
: Returns a list containing the last [n] elements:
fun main(args: Array<String>) {
val list= listOf(1,2,3,4,5)
val limitedList=list.takeLast(3)
println(limitedList)
}
//Output: [3,4,5]
takeWhile{ predicate }
: Returns a list containing the first elements satisfying the given [predicate]:
val list= listOf(1,2,3,4,5) val limitedList=list.takeWhile { it<3 } println(limitedList) //Output:...