Sets and maps

A Set holds each value once, and a Map holds one value per key. Both are immutable like the sequences: + and - return a new collection, and the old one is untouched. Both are hash tries, so the order in which they hand back their elements is not the order they were written in.

A set without duplicates

A set built from a list keeps one copy of each value. contains asks whether a value is in it, + adds, - removes, and a union or an intersection is ++ or intersect:

sets.scala

@main def sets(): Unit = val tags = Set("scala", "jvm", "scala") println(tags.size) println(tags.contains("jvm")) println((tags + "fp").toList.sorted) println((tags - "jvm").toList.sorted) println((tags ++ Set("fp", "types")).toList.sorted) println(Set(3, 1, 2).toList.sorted) println(tags.subsetOf(Set("scala", "jvm", "fp"))) println(tags.intersect(Set("jvm", "fp")).toList.sorted)

scala-cli run --server=false sets.scala

2
true
List(fp, jvm, scala)
List(scala)
List(fp, jvm, scala, types)
List(1, 2, 3)
true
List(jvm)

tags.size is two for three literals because "scala" is written twice, and the duplicate is gone before the set exists. Every print in the program sorts the elements first: a hash set may return them in any order, and a page that shows its order would show a different one on another run. subsetOf is the question a set answers better than a list, in constant time per element.

A map from key to value

Map("Ada" -> 36) is a collection of pairs, and the arrow is the tuple of the lesson on tuples. apply throws when the key is missing, so a program asks with get, supplies a fallback with getOrElse, or gives the whole map a default:

maps.scala

@main def maps(): Unit = val ages = Map("Ada" -> 36, "Grace" -> 45) println(ages("Ada")) println(ages.get("Alan")) println(ages.getOrElse("Alan", 0)) println(ages.updated("Alan", 41).toList.sorted) println((ages + ("Alan" -> 41)).toList.sorted) println((ages - "Ada").toList.sorted) println(ages.keys.toList.sorted) println(ages.values.sum) val withDefault = ages.withDefaultValue(0) println(withDefault("Alan")) for (name, age) <- ages.toList.sortBy(_._1) do println(s"$name is $age")

scala-cli run --server=false maps.scala

36
None
0
List((Ada,36), (Alan,41), (Grace,45))
List((Ada,36), (Alan,41), (Grace,45))
List((Grace,45))
List(Ada, Grace)
81
0
Ada is 36
Grace is 45

get answers an Option, which is why the two lookups of a missing name print None and 0 rather than failing. updated and + do the same thing for one entry, - removes a key, and withDefaultValue is for a map where a missing key really means zero. The map is turned into a list of pairs and sorted before it is printed, for the reason the set was.

Related

Article author: Arthur Isaev