Scala Collection Methods
Scala's collections share one large, consistent set of methods. Learn them once and they work on List, Vector, Set, Map, Array, String, Option and more. This chapter is a guided tour of the methods you will use every day, grouped by what they do.
All examples use this small data set:
case class Sale(region: String, product: String, units: Int, price: Double)Transforming: map, flatMap, collect
@main def run(): Unit =
val words = List("to be", "or not", "to be")
println(words.map(_.length))
println(words.flatMap(_.split(" ")))
println(words.map(_.split(" ").toList))
val mixed: List[Any] = List(1, "two", 3, "four")
val onlyInts = mixed.collect { case n: Int => n * 100 }
println(onlyInts)List(5, 6, 5)
List(to, be, or, not, to, be)
List(List(to, be), List(or, not), List(to, be))
List(100, 300)
mapproduces exactly one result per element.flatMapproduces zero or more results per element and flattens them.collectfilters and maps in one step, using a partial function withcase.
Selecting: filter, find, take, drop, partition
@main def run(): Unit =
val nums = List(4, 11, 7, 20, 3, 15)
println(nums.filter(_ > 6))
println(nums.filterNot(_ > 6))
println(nums.find(_ > 10))
println(nums.takeWhile(_ < 15))
println(nums.dropWhile(_ < 15))
println(nums.partition(_ % 2 == 0))
println(nums.span(_ < 10))
println(nums.distinct.sorted.takeRight(2))List(11, 7, 20, 15)
List(4, 3)
Some(11)
List(4, 11, 7)
List(20, 3, 15)
(List(4, 20),List(11, 7, 3, 15))
(List(4),List(11, 7, 20, 3, 15))
List(15, 20)
Testing: exists, forall, count, contains
| Method | Question it answers |
|---|---|
exists(p) |
Is p true for at least one element? |
forall(p) |
Is p true for every element? |
count(p) |
For how many elements is p true? |
contains(x) |
Is x in the collection? |
isEmpty / nonEmpty |
Are there any elements at all? |
Aggregating: sum, max, foldLeft, reduce
foldLeft(start)(op) walks from left to right, carrying an accumulator. It can build any result type.
case class Sale(region: String, product: String, units: Int, price: Double)
@main def run(): Unit =
val sales = List(
Sale("north", "pen", 10, 1.5),
Sale("south", "pad", 4, 3.0),
Sale("north", "pad", 2, 3.0),
Sale("south", "pen", 25, 1.5)
)
val revenue = sales.map(s => s.units * s.price).sum
val totalUnits = sales.foldLeft(0)((acc, s) => acc + s.units)
val best = sales.maxBy(_.units)
val cheapest = sales.minBy(_.price).product
println(revenue)
println(totalUnits)
println(best)
println(cheapest)
println(sales.exists(_.units > 20))
println(sales.forall(_.price < 5))70.5
41
Sale(south,pen,25,1.5)
pen
true
true
Grouping: groupBy, groupMapReduce
case class Sale(region: String, product: String, units: Int, price: Double)
@main def run(): Unit =
val sales = List(
Sale("north", "pen", 10, 1.5),
Sale("south", "pad", 4, 3.0),
Sale("north", "pad", 2, 3.0),
Sale("south", "pen", 25, 1.5)
)
val byRegion = sales.groupBy(_.region)
for region <- byRegion.keys.toList.sorted do
println(s"$region -> ${byRegion(region).map(_.product)}")
val unitsPerProduct = sales.groupMapReduce(_.product)(_.units)(_ + _)
println(unitsPerProduct.toList.sorted)north -> List(pen, pad)
south -> List(pad, pen)
List((pad,6), (pen,35))
Sorting
@main def run(): Unit =
val people = List(("Zoe", 31), ("Al", 25), ("Mo", 31), ("Bea", 19))
println(people.sortBy(_._2))
println(people.sortBy((name, age) => (-age, name)))
println(people.map(_._1).sortWith(_.length < _.length))
println(people.map(_._1).sorted(using Ordering.String.reverse))List((Bea,19), (Al,25), (Zoe,31), (Mo,31))
List((Mo,31), (Zoe,31), (Al,25), (Bea,19))
List(Al, Mo, Zoe, Bea)
List(Zoe, Mo, Bea, Al)
Sorting is stable: elements with equal keys keep their original order (Zoe stays before Mo in the first line).
Combining and slicing
@main def run(): Unit =
val xs = List(1, 2, 3, 4, 5, 6, 7)
println(xs.grouped(3).toList)
println(xs.sliding(3).map(_.sum).toList)
println(xs.zip(xs.tail).map((a, b) => b - a))
println(xs.scanLeft(0)(_ + _))
println(List(List(1, 2), List(3), Nil).flatten)
println(xs.splitAt(2))List(List(1, 2, 3), List(4, 5, 6), List(7))
List(6, 9, 12, 15, 18)
List(1, 1, 1, 1, 1, 1)
List(0, 1, 3, 6, 10, 15, 21, 28)
List(1, 2, 3)
(List(1, 2),List(3, 4, 5, 6, 7))
Cheat sheet
| Goal | Method |
|---|---|
| change every element | map |
| one-to-many, then flatten | flatMap |
| keep / remove some | filter, filterNot, collect |
| first match | find |
| split in two | partition, span, splitAt |
| combine into one value | sum, product, foldLeft, reduce |
| largest / smallest by key | maxBy, minBy |
| build a map | groupBy, groupMapReduce, toMap |
| order | sorted, sortBy, sortWith |
| windows | grouped, sliding |
| running totals | scanLeft |
Tip: Long chains are fine, but give intermediate results names when a chain stops fitting on one or two lines. Named
vals are free documentation.
Test yourself
What does List("a b", "c").flatMap(_.split(" ")) return?
List(a b, c)List(a, b, c)List(List(a, b), List(c))List(3)
What does List(1, 2, 3).foldLeft(10)(_ + _) evaluate to?
- 6
- 16
- 10
- 60
Which method splits a collection into elements that pass a test and those that don't?
groupBypartitionslidingspan