Chaining collection operations in Kotlin

Level 5265 keystrokes

filter, sortedBy and map each return a new list, so they can be chained. The chain keeps people aged 25 or more, sorts them by name and turns each one into a "name (age)" string.

Kotlin code

// A data class for a person with a name and an age
1data class Person(val name: String, val age: Int)
2
// A list of three people
3val people = listOf(
4 Person("Alice", 25),
5 Person("Bob", 30),
6 Person("Carol", 22)
7)
8
// Each step returns a new list; people itself is not changed
9val result = people
// Keep people aged 25 or more: Carol (22) is removed
10 .filter { it.age >= 25 }
// Sort by name in alphabetical order
11 .sortedBy { it.name }
// Turn each Person into a string such as "Alice (25)"
12 .map { "${it.name} (${it.age})" }
13
// Prints Alice (25) and Bob (30)
14for (r in result) println(r)

Output

Alice (25)
Bob (30)
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • "× 8
  • (× 8
  • )× 8
  • .× 7
  • ,× 6
  • {× 5
  • }× 5
  • =× 3
  • :× 2
  • $× 2

More Kotlin examples at level 5

← Kotlin typing practice