View Category

Define an empty map

scala
val map = mutable.Map.empty
val map = mutable.HashMap.empty[String, Int]
val map = Map()

Define an unmodifiable empty map

scala
val map = immutable.Map.empty
val map = immutable.TreeMap.empty[String, Int]
val map = Map()

Define an initial map

Define the map {circle:1, triangle:3, square:4}
scala
val shapes = immutable.TreeMap("circle" -> 1, "triangle" -> 3, "square" -> 4)
val shapes = mutable.Map.empty[String, Int]

shapes += "circle" -> 1
shapes += "triangle" -> 3
shapes += "square" -> 4
var shapes = immutable.Map.empty[String, Int]

shapes = shapes + ("circle" -> 1)
shapes = shapes + ("triangle" -> 3)
shapes = shapes + ("square" -> 4)
val shapes = immutable.Map(
"circle" -> 1,
"triangle" -> 3,
"square" -> 4
)
val map = Map("circle" -> 1, "triangle" -> 3, "square" -> 4)

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
scala
if (pets.contains("mary")) println("ok")
map.get("mary").foreach(println("ok"))

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
scala
if (pets.contains("joe")) println(pets("joe"))
println(pets.getOrElse("joe", "*** no pet owned ***"))
pets("joe")

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
scala
pets += "rob" -> "dog"

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
scala
val pet = pets("bill") ; pets -= "bill" ; println(pet)
println(pets.removeKey("bill") match { case Some(pet) => pet ; case None => "***" })

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
scala
list foreach { (x) => histogram += x -> (histogram.getOrElse(x, 0) + 1) }
val data = List("a", "b", "a", "c", "b", "b")
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
val histEntries = for {
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
value.foldLeft(Map[T, Int]()){
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}

list.groupBy(identity).mapValues(_.size)

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
scala
list foreach { (x) => map += x.length -> (x :: map.getOrElse(x.length, Nil)) }
list foreach { (x) => map += x.length -> (map.getOrElse(x.length, Nil) ::: List(x)) }
List("one", "two", "three", "four", "five") groupBy (_ size)