๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Searching and Sorting

Searching functions look through a collection for values that match a test. Sorting functions return the values in a new order.

Finding a value

find stops at the first match. firstOrNull gives null when nothing matches.

fun main() {
    val scores = listOf(72, 85, 91, 68)
    println(scores.find { it > 80 })
    println(scores.firstOrNull { it > 95 })
    println(scores.firstOrNull { it > 95 } ?: -1)
}

Testing the whole collection

any checks whether at least one value matches. all and none check the collection in other ways.

fun main() {
    val words = listOf("ant", "ape", "bat")
    println(words.any { it.startsWith("b") })
    println(words.all { it.length >= 3 })
    println(words.none { it.isEmpty() })
    println(words.count { it.startsWith("a") })
    println(words.any { it == "bat" })
}

Sorting values

sorted orders values from smallest to largest. sortedBy orders values by a computed key.

fun main() {
    val nums = listOf(3, 1, 4, 2)
    println(nums.sorted())
    println(nums.sortedDescending())
    val words = listOf("pear", "fig", "banana")
    println(words.sortedBy { it.length })
}

Largest, smallest and total

maxByOrNull picks the value with the largest key. An Elvis fallback stands in for a null result.

fun main() {
    val words = listOf("pear", "fig", "banana")
    println(words.maxByOrNull { it.length } ?: "empty")
    println(words.minByOrNull { it.length } ?: "empty")
    val nums = listOf(2, 4, 6)
    println(nums.sumOf { it * 10 })
}

Example

fun main() {
    val prices = listOf(12, 5, 20, 8, 5)
    println(prices.find { it < 10 })
    println(prices.count { it == 5 })
    println(prices.sorted())
    println(prices.maxByOrNull { it } ?: -1)
    println(prices.sumOf { it })
}

Key points

  • find returns the first value that matches a test.
  • firstOrNull returns null when no value matches.
  • any, all and none test a whole collection and return a Boolean.
  • count with a lambda counts the values that match.
  • sorted and sortedBy return a new sorted list.
  • maxByOrNull and minByOrNull return null for an empty collection.
  • sumOf adds a computed number for every value.

In this example, find returns 5 because it is the first price below 10. count finds two prices equal to 5. sorted returns the prices in rising order, and sumOf adds all the prices to 50.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does listOf(3, 1, 2).sortedDescending() return?