Searching

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:

val list = listOf("Kotlin", "Java", "Swift", "K")
val item = list.first()
println(item)

Running this code will print out "Kotlin".

val list = listOf("Kotlin", "Java", "Swift", "K")
val item = list.last()
println(item)

This time, the code will print out "K".

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
val list = listOf("Kotlin", "Java", "Swift", "K")
val lastK = list.findLast { it.contains("K") }
println(lastK)
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.