← Back to Scala Course | Chapter 9: Functional Programming | Lesson 2 of 8

map, filter, reduce

In this page:

  1. map, filter, reduce

map, filter, reduce

map(f) transforms every element of a collection and returns a new collection of results. filter(p) keeps only elements matching a predicate. reduce(f) combines all elements into a single value by repeatedly applying a binary function, like folding a list down with + to get a sum. These three are the core building blocks of functional collection processing.

Note: reduce fails on an empty collection -- use foldLeft/foldRight with an initial value if the collection might be empty.

Example: map, filter, reduce

markup
object Main extends App {
  val numbers = List(1, 2, 3, 4, 5)

  val doubled = numbers.map(n => n * 2)
  val evens = numbers.filter(n => n % 2 == 0)
  val total = numbers.reduce((a, b) => a + b)

  println(doubled)
  println(evens)
  println(total)
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.