The Kotlin standard library provides a variety of functions for picking items out of a collection. These include functions such as find(), first(), and last(). Let's take a look at a few of these functions:
- Let's look at the following example using the first() function:
val list = listOf("Kotlin", "Java", "Swift", "K")
val item = list.first()
println(item)
Running this code will print out "Kotlin".
- Or, we could use the last() function:
val list = listOf("Kotlin", "Java", "Swift", "K")
val item = list.last()
println(item)
This time, the code will print out "K".
- What if we want to take more than one item out of a collection? For this, we can use the take() function:
val list = listOf("Kotlin", "Java", "Swift", "K")
list.take(2).forEach { println(it) }
In this example, we've called take(2) to take the first two items out of the list. When we then print those items out, we get the following output:
Kotlin
Java
- We can use the findLast() function to retrieve the last element in a collection that matches a given predicate:
val list = listOf("Kotlin", "Java", "Swift", "K")
val lastK = list.findLast { it.contains("K") }
println(lastK)
- Alternatively, we could use find() to retrieve the first element in a collection that matches the given predicate:
val list = listOf("Kotlin", "Java", "Swift", "K")
val firstK = list.find { it.contains("K") }
println(firstK)
These functions make it easy to query the items within a collection and retrieve the ones that match our current use case.