map, filter, reduce
In this page:
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
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: