CodeBlanks Logo Icon CodeBlanks

Summary - Lists

Combine mutableListOf, add and map to write a class list.

Summary: build a list, add, transform

In this summary you will combine mutableListOf, add and map to process a class list. First build a mutable list, add a new student, then upper-case every name with map.

val students = mutableListOf("Ava", "Liam")
students.add("Nora")
val big = students.map { it.uppercase() }
// [AVA, LIAM, NORA]

This chain shows both the mutable (add) and the transformable (map) side of lists.

Practice Grow and transform the class list

Start with mutableListOf("Ava", "Liam"), add "Nora" with add, then upper-case every name with map { it.uppercase() } and print the result with println.

Starter code

Main.kt
fun main() {
    // Build a mutable list of two students, add one more,
    // upper-case the names and print
}

Sample solution

Main.kt
fun main() {
    val students = mutableListOf("Ava", "Liam")
    students.add("Nora")
    println(students.map { it.uppercase() })
}

Expected output

[AVA, LIAM, NORA]

Practice Pick the long names with filter

Create a mutableListOf("Ava", "Liam", "Nora"). Use filter { it.length > 3 } to keep names longer than 3 characters and print the result with println.

Starter code

Main.kt
fun main() {
    val students = mutableListOf("Ava", "Liam", "Nora")
    // Filter names longer than 3 characters and print
}

Sample solution

Main.kt
fun main() {
    val students = mutableListOf("Ava", "Liam", "Nora")
    val longNames = students.filter { it.length > 3 }
    println(longNames)
}

Expected output

[Liam, Nora]

Questions and answers

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

1 Which chain works correctly?

  • mutableListOf + add + filter { it.uppercase() }
  • listOf + add + map { it.uppercase() }
  • mutableListOf + put + map { it.uppercase() }
  • mutableListOf + add + map { it.uppercase() } Correct answer

Explanation: mutableListOf accepts add; map produces the upper-case list.

2 Match chain step to role

Term Meaning
mutableListOf Mutable start
add Appends an element
map { } Transforms each element
uppercase() Upper-cases letters

All lessons in Beginner