Learn/Scala/7. Collections
Lesson 7 of 8
Sign in

Scala, lesson 7

Collections

One variable per value stops working once you have a list of scores or a basket of products. Scala's collections library is one of its strongest features. Most collections come in an immutable version (the default) and a mutable one.

List and Vector

A List holds items in order. Create one by listing its elements:

A List is immutable. "Adding" an item gives you a new list, and the old one is unchanged:

Vector works the same way but is fast at reading and updating any position, so it's a good default when you need indexing.

Useful methods

Collections come with a large set of methods. A few you'll use constantly:

map and filter take a function as an argument. p => p * 2 is an anonymous function, and is shorthand for . You'll often chain these: .

2 exercises to try what you just read.

Exercise 1

Score stats

Press Ctrl Enter or Check to test your code.

Exercise 2

Shopping list

Press Ctrl Enter or Check to test your code.

_ > 5
x => x > 5
prices.filter(_ > 5).map(_ * 2).sum

To loop over items, use for p <- prices do println(p) or prices.foreach(println).

ArrayBuffer: a growable mutable list

When you build a collection step by step, for example while reading input, an ArrayBuffer is convenient. You add to it in place with +=:

Turn it into an immutable list at the end with .toList if you like.

Map: look things up by key

A Map stores key -> value pairs and finds a value by its key quickly:

stock("kiwi") would throw an exception, so prefer getOrElse when a key may be missing.

Immutable maps return a new map when you add or change an entry:

A common pattern keeps the current map in a var and replaces it after each change. Maps have no guaranteed order, so to print them in alphabetical order, sort the keys first:

If you prefer to modify in place, scala.collection.mutable.Map supports counts(key) = value.

Further reading

  • Scala 3 Book: Collections
  • Scala 3 Book: Collections types
  • Scala 3 Book: Collections methods

Read one line of whole-number game scores separated by spaces (at least one score). Print:

Sample input:

Sample output:

Several people added items to a shared shopping list, so the same item can appear more than once. The first line is the number of entries. Each entry line has an item name and a quantity separated by a space. Add up the quantity for each item and print one line per item, <item>: <total>, in alphabetical order.

Sample input:

Sample output:

The starter reads the entries for you.

val scores = List(70, 85, 92)
println(scores(0))        // 70  (indexes start at 0)
println(scores.length)    // 3
println(scores.head)      // 70  (the first item)
val more = scores :+ 60    // List(70, 85, 92, 60)  (append)
val first = 50 :: scores   // List(50, 70, 85, 92)  (prepend, fast for List)
val prices = List(4, 12, 7, 20)
prices.sum              // 43
prices.max              // 20
prices.min              // 4
prices.sorted           // List(4, 7, 12, 20)
prices.reverse          // List(20, 7, 12, 4)
prices.contains(7)      // true
prices.map(p => p * 2)  // List(8, 24, 14, 40)
prices.filter(_ > 5)    // List(12, 7, 20)
prices.mkString(", ")   // "4, 12, 7, 20"
import scala.collection.mutable.ArrayBuffer

val names = ArrayBuffer[String]()
names += "Ada"
names += "Linus"
println(names.mkString(" "))   // Ada Linus
val stock = Map("apple" -> 5, "pear" -> 2)
stock("apple")              // 5
stock.getOrElse("kiwi", 0)  // 0  (default when the key is missing)
stock.contains("pear")      // true
val updated = stock.updated("kiwi", 7)   // or: stock + ("kiwi" -> 7)
for key <- updated.keys.toList.sorted do
  println(s"$key: ${updated(key)}")
Count: <how many>
Highest: <max>
Lowest: <min>
Sorted: <scores from low to high, separated by spaces>
70 92 85 64
Count: 4
Highest: 92
Lowest: 64
Sorted: 64 70 85 92
4
milk 2
eggs 12
milk 1
bread 1
bread: 1
eggs: 12
milk: 3