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

Kotlin Transformations

A transformation builds a new list from an existing list. Each transformation applies a rule to the elements and leaves the original list unchanged.

map changes each element

map doubles each number and collects the results. The new list holds three doubled values.

fun main() {
    val numbers = listOf(1, 2, 3)
    val doubled = numbers.map {
        it * 2
    }
    println(doubled)
}

mapIndexed adds the position

mapIndexed receives the index beside each word. The result pairs each word with its position.

fun main() {
    val words = listOf("ana", "ben")
    val labelled = words.mapIndexed { index, word ->
        "$index: $word"
    }
    println(labelled)
}

filter and filterNot divide by a test

filter keeps the even numbers. filterNot keeps the numbers that fail the same test.

fun main() {
    val numbers = listOf(1, 2, 3, 4)
    val evens = numbers.filter {
        it % 2 == 0
    }
    println(evens)
    val odds = numbers.filterNot {
        it % 2 == 0
    }
    println(odds)
}

mapNotNull drops nulls

The block returns each element as it stands. mapNotNull drops the null and keeps the two numbers.

fun main() {
    val values = listOf(5, null, 8)
    val present = values.mapNotNull {
        it
    }
    println(present)
}

A filter then map pipeline

filter keeps the even numbers first. map then multiplies each kept number by ten.

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val result = numbers
        .filter {
            it % 2 == 0
        }
        .map {
            it * 10
        }
    println(result)
}

Example

fun main() {
    val scores = listOf(45, 80, 62, 90)
    val passed = scores
        .filter {
            it >= 60
        }
        .map {
            it + 5
        }
    println(passed)
    val labels = passed.mapIndexed { index, score ->
        "P${index + 1}: $score"
    }
    println(labels)
}

Key points

  • map applies a block to each element and collects the results.
  • mapIndexed gives the block both the index and the element.
  • filter keeps only the elements that pass its test.
  • filterNot keeps only the elements that fail its test.
  • mapNotNull drops null results and keeps the rest.
  • Transformations can chain, so one list feeds the next step.

In this example, filter keeps the scores of 60 and above, and map adds a bonus of 5 to each one. mapIndexed then labels each result with its position, starting at P1.

Note

Every transformation returns a new list. The source list is not changed.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does listOf(1, 2, 3).map { it + 1 } give?