Start learning free

LESSON 270 OF 677 · PAIRS, SORTING & BUILT-INS

Map and Filter in Kotlin

Lesson

TL ; DR:

The map function builds a new list with every item changed. The filter function builds a new list with only the items that pass a test. In the braces, it is the item.


val nums = mutableListOf(1, 2, 3, 4)

val squares = nums.map { it * it }                  // [1, 4, 9, 16]

val evens = nums.filter { it % 2 == 0 }             // [2, 4]

val big = nums.filter { it > 2 }.map { it * 10 }    // [30, 40]


Full lesson:

You often build a new list from an old one. You already know how to do it with a loop:

val squares = mutableListOf<Int>()
for (n in nums) {
    squares.add(n * n)
}

The map function does the same in one line. The code in braces is a lambda, a small function, as in Custom Sorting. It runs on every item, and the results go in a new list.

val squares = nums.map { it * it }

As in Custom Sorting, it is the item. You can also give it a name: nums.map { n -> n * n }.

filter takes a lambda that gives true or false. It keeps only the items that get true.

val evens = nums.filter { it % 2 == 0 }

You can chain the two. First filter picks the items, then map changes them.

val big = nums.filter { it > 2 }.map { it * 10 }    // [30, 40]

Both return a new list. The old list, nums, stays as it was.

Watch out: the new list is read-only, so it has no add. Call toMutableList() on it if you need to change it.


Your task

A theater keeps the price of one ticket for each show in prices. Build doubled with map: the price of two tickets for each show.

A quiz keeps its scores in scores. A score of 50 or more passes. Build passed with filter: only the passing scores.

The code already prints both lists, one value per line.

Expected output:

Two tickets cost 24
Two tickets cost 16
Two tickets cost 30
72 passed
50 passed
90 passed
STEP 1 OF 2
    Ctrl + Enter to check