Start learning free

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

Map and Filter in Scala

Lesson

TL ; DR:

The map method builds a new ArrayBuffer with every item changed. The filter method builds one with only the items that pass a test.


val nums = scala.collection.mutable.ArrayBuffer(1, 2, 3, 4)

val squares = nums.map(n => n * n)
// ArrayBuffer(1, 4, 9, 16)

val evens = nums.filter(n => n % 2 == 0)
// ArrayBuffer(2, 4)

val big = nums.filter(n => n > 2).map(n => n * 10)
// ArrayBuffer(30, 40)


Full lesson:

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

val squares = scala.collection.mutable.ArrayBuffer[Int]()
for (n <- nums) {
    squares += n * n
}

The map method does the same in one line. You give it a small function, as you gave sortBy one in Custom Sorting. It runs the function on every item and collects the results.

val squares = nums.map(n => n * n)

Read n => n * n as: take n, give back n * n.

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

val evens = nums.filter(n => n % 2 == 0)

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

val big = nums.filter(n => n > 2).map(n => n * 10)    // ArrayBuffer(30, 40)

Watch out: an ArrayBuffer can change, but map and filter don't change it. They return a new one. So keep the result in a val.


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 ArrayBuffers, 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