Scala · Working with Data

Collections

Scala’s collections library is one of its best features: rich, immutable by default and consistent across types.

Intermediate 5 min Lesson 8 of 25Examples use Scala 3 (3.3 LTS or newer) with sbt or scala-cli.
Before you start:Functions
0/25 in Scala
On this page · 5 min · Intermediate

In simple words#

Immutable collections are like photocopies: “adding” an item gives you a new copy with the item, and the original stays safe for anyone else using it.

List
Immutable linked list — fast at the head.
Vector
Immutable indexed sequence — fast everywhere.
Map
Immutable key → value pairs.

Learning objectives#

  • Create immutable collections
  • Transform with map/filter
  • Aggregate with sum, foldLeft and groupBy
  • Know when to use mutable collections

Explanation#

Default collections are immutable: List, Vector, Set, Map. Adding returns a new collection.

The same methods work everywhere: map, filter, flatMap, find, exists, sortBy, groupBy, foldLeft, take, zip.

Use Vector for indexed access; List for head/tail recursion and prepending.

scala.collection.mutable (ArrayBuffer, mutable.Map) is available for local performance-critical code.

Code example: Order analytics#

ScalaOrder analytics Illustrative
case class Order(city: String, product: String, amount: Double)


val orders = List(
  Order("Pune", "Laptop", 55000), Order("Delhi", "Mouse", 1400),
  Order("Pune", "Keyboard", 2200), Order("Delhi", "Laptop", 52000))


val big = orders.filter(_.amount > 2000).map(_.product).distinct.sorted
val total = orders.map(_.amount).sum
val byCity = orders.groupBy(_.city).view.mapValues(_.map(_.amount).sum).toMap
val cheapest = orders.minBy(_.amount)
val withMonitor = orders :+ Order("Chennai", "Monitor", 12000)   // new list


println(big)
println(s"Total: $total")
println(byCity)
println(s"Cheapest: ${cheapest.product}; orders now ${withMonitor.size}, original ${orders.size}")
Expected output
List(Keyboard, Laptop)
Total: 110600.0
Map(Pune -> 57200.0, Delhi -> 53400.0)
Cheapest: Mouse; orders now 5, original 4

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. filter and map pick big products; distinct and sorted tidy them.
  2. sum adds amounts.
  3. groupBy + mapValues totals per city.
  4. :+ returns a new list; the original is unchanged.

Real-world use case#

The same collection methods are used in Spark — learning them pays off directly in big-data jobs.

Common mistakes#

Indexing a List in a loop

list(i) is O(n) for List. Use Vector or iterate directly.

Expecting add to modify the original

Immutable operations return new collections; assign the result.

Best practices#

  • Immutable by default
  • Vector for random access
  • Chain transformations
  • Mutable only locally

Remember this#

Same methods on every collection.

Adding returns a new collection.

List = head-fast, Vector = all-round.

Practice exercise#

Your task: Count word frequencies in a List[String].

Show solution
Scala Illustrative
val counts = words.groupBy(identity).view.mapValues(_.size).toMap

Mini quiz#

Collections quizMultiple choice Question 1 of 1

What does list :+ 5 do to the original list?

Score so far: 0/0

Want more? Practise all Scala MCQs · Scala interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.