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

map, filter, reduce

map changes every item in a collection, filter keeps only the ones you want, and reduce squishes them into a single answer. Together they are like a factory line that paints, sorts, and packs toys.

In this page:

  1. map, filter, reduce
Syntax
scala
val mapped = collection.map(x => expression)
val filtered = collection.filter(x => condition)
val reduced = collection.reduce((a, b) => expression)

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using reduce on an empty list, which throws an exception; use foldLeft with a start value or reduceOption.
  2. Expecting filter to change the original list, when it returns a new one.
  3. Forgetting that reduce(_ - _) depends on the order of operands, so results differ from what you expect.
🔒

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.