Scala Collections: map and filter
Transform and filter an immutable List without loops.
On this page
Scala basics.
- Transform and filter an immutable List without loops.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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)
}
}List(87, 96, 81) 96
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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) }}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
| Step / line | What happens | State after step | Output 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 |
Behind the scenes
How Scala processes this code
Scala compiles for the JVM, which invokes the main entry point.
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).