typestar

Grouping and sorting in Kotlin

Order a list by any key, or bucket it by one.

fun main() {
    val summits = listOf(
        "Tolmie" to 1408, "Brier" to 980, "Sawback" to 2214,
        "Quartz" to 2590, "Meadow" to 760,
    )
    // sortedByDescending orders; groupBy buckets by a computed key.
    val ranked = summits.sortedByDescending { it.second }
    println("Highest: ${ranked.first().first}")

    val byBand = summits.groupBy { (_, m) -> m / 1000 }
    println("Under 1000 m: ${byBand[0]?.map { it.first }}")
    println("Above 2000 m: ${byBand[2]?.size}")
}

How it works

  1. sortedByDescending { it.second } ranks the summits by height.
  2. groupBy builds a map from computed key to the entries that share it.
  3. byBand[0]?.map { ... } reads a bucket that may not exist, safely.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
442
Tokens
136
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 126 seconds.

Type this snippet

Step 3 of 3 in Collections, step 12 of 27 in Language basics.

← Previous Next →