Scala Collections: map and filter

Transform and filter an immutable List without loops.

Scala
object Main {
  def main(args: Array[String]): Unit = {
    val scores = List(82, 91, 76)
    val curved = scores.map(s => s + 5)
    println(curved)
    println(curved.filter(s => s >= 90).sum)
  }
}
Output
List(87, 96, 81)
96

Explanation

Scala's standard collections are immutable by default. map builds a new list by applying a function to every element, and filter keeps only the elements for which a condition is true. Neither changes the original list.

Chaining them is the usual way to express a pipeline. Here the scores are curved by 5, giving 87, 96, and 81, and then only those of at least 90 are kept and summed.

Explore the dry run
Guided walkthroughReady
1object Main {
2 def main(args: Array[String]): Unit = {
3 val scores = List(82, 91, 76)
4 val curved = scores.map(s => s + 5)
5 println(curved)
6 println(curved.filter(s => s >= 90).sum)
7 }
8}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
An immutable list of three ints.scores = List(82, 91, 76)
—
A new list with 5 added to each element.curved = List(87, 96, 81)
—
A List prints in its constructor form.curved = List(87, 96, 81)
List(87, 96, 81)
Only 96 remains, and its sum is 96.curved = List(87, 96, 81)
List(87, 96, 81)
96

Cost and common mistakes

map and filter are O(n) time; each builds a new list of up to n elements.

  • Collections are immutable, so scores.map(...) on its own discards the result unless you keep it.
  • sum of an empty List is 0, but max of an empty List throws an exception.

Try it yourself

Predict scores.filter(s => s > 80).

Reveal answer and reasoning

It keeps 82 and 91, giving List(82, 91).

Further reading