🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Map and Filter

Map and filter are list methods that build a new list from an existing list. Map changes every item, and filter keeps only the items that pass a test.

Map changes every item

map applies _ * 2 to each number, so every item is doubled in the new list. The second list shows the same idea with division.

@main def main(): Unit =
  val nums = List(1, 2, 3)
  println(nums.map(_ * 2))
  val prices = List(10, 20, 30)
  println(prices.map(_ / 10))

Filter keeps the items that pass

filter keeps an item when the test after the underscore is true for it. The two calls keep the high end and the low end of the same list.

@main def main(): Unit =
  val nums = List(1, 2, 3, 4, 5, 6)
  println(nums.filter(_ > 3))
  println(nums.filter(_ < 3))

Chaining filter and map

The filter call first keeps the numbers above 1, and map then multiplies each survivor by ten. The last line proves the original list is untouched.

@main def main(): Unit =
  val nums = List(1, 2, 3, 4, 5)
  val result = nums.filter(_ > 1).map(_ * 10)
  println(result)
  println(nums)

Example

@main def main(): Unit =
  val scores = List(45, 80, 62, 30, 90)
  val curved = scores.filter(_ >= 50).map(_ + 5)
  println(curved)
  println(curved.length)
  println(scores)

Key points

  • Map: The map method builds a new list by applying a change to every item of the original list.
  • Filter: The filter method builds a new list holding only the items for which a test is true.
  • Underscore shorthand: Inside map and filter, the symbol _ stands for the current item being processed.
  • Chaining: The result of filter can be passed straight into map by writing the calls one after the other.
  • Original unchanged: Map and filter return new lists, so the original list keeps its old values.

In this example, filter first keeps the scores of 50 or more, which are 80, 62, and 90. Map then adds 5 to each of them, giving the curved list. The length shows three scores survived, and the last line shows the original scores list unchanged.

Note

Map and filter show their results in the same List form as any other list.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What is List(1, 2, 3, 4).filter(_ > 2).map(_ * 10)?