Scala Collection Methods
Scala collections share a rich set of methods that work on List, Set, Map, Array, Vector, and Range. Learning these methods eliminates the need for most manual loops. This topic covers the most important ones with practical diagrams.
Transformation Methods
val nums = List(1, 2, 3, 4, 5)
// map: apply a function to every element
nums.map(_ * 3) // List(3, 6, 9, 12, 15)
nums.map(n => s"Item $n") // List(Item 1, Item 2, ...)
// flatMap: map then flatten one level
List(1, 2, 3).flatMap(n => List(n, n * 10))
// List(1, 10, 2, 20, 3, 30)
// flatten: collapse nested collections
List(List(1,2), List(3,4), List(5)).flatten
// List(1, 2, 3, 4, 5)
// collect: map + filter using partial function
nums.collect { case n if n % 2 == 0 => n * 10 }
// List(20, 40)
Filtering Methods
val data = List(8, 3, 15, 2, 9, 17, 4, 11)
data.filter(_ > 8) // List(15, 9, 17, 11)
data.filterNot(_ > 8) // List(8, 3, 2, 4)
data.takeWhile(_ < 10) // List(8, 3) — stops at first fail
data.dropWhile(_ < 10) // List(15, 2, 9, 17, 4, 11)
data.partition(_ % 2 == 0) // (List(8,2,4), List(3,15,9,17,11))
data.span(_ < 10) // (List(8,3), List(15,2,9,17,4,11))
Aggregation Methods
val scores = List(85, 92, 78, 95, 67, 88)
scores.sum // 505
scores.product // — (very large number)
scores.max // 95
scores.min // 67
scores.count(_ >= 80) // 4
scores.size // 6
// reduce: combine all elements (no initial value)
scores.reduce(_ + _) // 505
scores.reduceLeft(_ max _) // 95 (running max)
// foldLeft: like reduce but with initial value
scores.foldLeft(0)(_ + _) // 505
scores.foldLeft(Int.MaxValue)(_ min _) // 67
Inspection Methods
val items = List("apple", "banana", "avocado", "cherry")
items.exists(_.startsWith("a")) // true — any match?
items.forall(_.length > 3) // true — all match?
items.contains("banana") // true
items.find(_.startsWith("av")) // Some(avocado)
items.indexOf("cherry") // 3
items.isEmpty // false
items.nonEmpty // true
Grouping Methods
val words = List("apple", "ant", "bear", "ape", "cat", "cobra")
words.groupBy(_.head)
// Map(a -> List(apple, ant, ape), b -> List(bear), c -> List(cat, cobra))
words.sortBy(_.length)
// List(ant, ape, cat, bear, apple, cobra)
words.sortWith((a, b) => a > b) // reverse alphabetical
words.groupBy(_.length).map { (len, ws) => len -> ws.length }
// Map(3 -> 2, 4 -> 2, 5 -> 2)
Slicing Methods
val list = List(10, 20, 30, 40, 50, 60)
list.take(3) // List(10, 20, 30)
list.drop(3) // List(40, 50, 60)
list.slice(1, 4) // List(20, 30, 40)
list.head // 10
list.tail // List(20, 30, 40, 50, 60)
list.init // List(10, 20, 30, 40, 50) — everything but last
list.last // 60
list.splitAt(2) // (List(10, 20), List(30, 40, 50, 60))
Zip Methods
val names = List("Alice", "Bob", "Carol")
val grades = List(90, 85, 92)
names.zip(grades)
// List((Alice,90), (Bob,85), (Carol,92))
names.zipWithIndex
// List((Alice,0), (Bob,1), (Carol,2))
names.zipAll(grades, "Unknown", 0) // safe zip with defaults
String Output Methods
val fruits = List("Apple", "Banana", "Cherry")
fruits.mkString // "AppleBananaCherry"
fruits.mkString(", ") // "Apple, Banana, Cherry"
fruits.mkString("[", ", ", "]") // "[Apple, Banana, Cherry]"
Scanning Methods
// scanLeft: like foldLeft but keeps all intermediate results
List(1, 2, 3, 4, 5).scanLeft(0)(_ + _)
// List(0, 1, 3, 6, 10, 15) ← running total
// Useful for running balances
val transactions = List(100, -20, 50, -30, 80)
transactions.scanLeft(0)(_ + _).tail
// List(100, 80, 130, 100, 180)
Distinct and Dedup
List(1, 2, 2, 3, 1, 4, 3).distinct // List(1, 2, 3, 4)
List(1, 2, 2, 3, 1, 4, 3).toSet // Set(1, 2, 3, 4)
Method Chaining Pipeline
case class Student(name: String, grade: Int, city: String)
val students = List(
Student("Aarav", 88, "Mumbai"),
Student("Diya", 92, "Delhi"),
Student("Rohan", 74, "Mumbai"),
Student("Priya", 95, "Pune"),
Student("Kiran", 81, "Delhi")
)
val report =
students
.filter(_.grade >= 80) // keep top students
.sortBy(-_.grade) // sort by grade desc
.groupBy(_.city) // group by city
.map { (city, studs) =>
city -> studs.map(_.name).mkString(", ")
}
report.toList.sortBy(_._1).foreach { (city, names) =>
println(s"$city: $names")
}
// Delhi: Diya, Kiran
// Mumbai: Aarav
// Pune: Priya
Chaining collection methods builds data pipelines that are readable, concise, and often faster to write than equivalent imperative loops. Each method transforms the collection and passes the result to the next, creating a clear left-to-right flow of data.
