CodeBlanks Logo Icon CodeBlanks

List methods

Learn list processing with map, filter and sortedWith.

List methods: map, filter, sortedWith

To transform a list, map { } turns each element into a new value. filter { } keeps only those that match a condition. sortedWith(cmp) sorts by a comparator; sortedBy { } is its shortcut.

val nums = listOf(3, 7, 12)
val doubles = nums.map { it * 2 }       // [6, 14, 24]
val big = nums.filter { it > 5 }       // [7, 12]
val sorted = nums.sortedBy { it }      // [3, 7, 12]

These methods do not change the original list; they return a new one. it is the automatic name of the element inside the lambda.

sortedWith and compareBy

sortedWith takes a Comparator. The easiest way is to give a key with compareBy { } and sort by it. To sort in descending order, use reverseOrder().

val people = listOf("Selin", "Ayşe", "Mert")
val byName = people.sortedBy { it }            // [Ayşe, Mert, Selin]
val byLen = people.sortedBy { it.length }      // length ascending
val desc = people.sortedWith(compareByDescending { it })

These methods return a new list; the original is unchanged. To sort by two keys, chain compareBy({ a }, { b }).

Practice Print the doubles with map

Create a listOf(3, 7, 12). Use map { it * 2 } to compute the double of each number and print the new list with println.

Starter code

Main.kt
fun main() {
    val nums = listOf(3, 7, 12)
    // Compute the double of each number with map and print it
}

Sample solution

Main.kt
fun main() {
    val nums = listOf(3, 7, 12)
    val doubles = nums.map { it * 2 }
    println(doubles)
}

Expected output

[6, 14, 24]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does listOf(1, 2, 3).map { it * 2 } return?

  • [1, 2, 3]
  • 6
  • [2, 4, 6] Correct answer
  • [1, 4, 9]

Explanation: map multiplies each element by 2 and returns a new list.

2 Fill in the blank: keep matching items

Question
nums.____ { it > 10 }
Answer
nums.filter { it > 10 }

Explanation: nums.filter { it > 10 } keeps only the large elements.

3 Match method to purpose

Term Meaning
map { } Transform each element
filter { } Keep matching items
sortedBy { } Sort by a key
sortedWith(cmp) Sort with a custom comparator

All lessons in Beginner