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:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
- Using
reduceon an empty list, which throws an exception; usefoldLeftwith a start value orreduceOption. - Expecting
filterto change the original list, when it returns a new one. - 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: