August 2013
Intermediate to advanced
720 pages
16h 23m
English
You want to add, remove, or update elements in a mutable map.
Add elements to a mutable map by simply assigning them, or with
the += method. Remove elements with
-= or --=. Update elements by reassigning
them.
Given a new, mutable Map:
scala> var states = scala.collection.mutable.Map[String, String]()
states: scala.collection.mutable.Map[String,String] = Map()You can add an element to a map by assigning a key to a value:
scala> states("AK") = "Alaska"You can also add elements with the += method:
scala> states += ("AL" -> "Alabama")
res0: scala.collection.mutable.Map[String,String] =
Map(AL -> Alabama, AK -> Alaska)Add multiple elements at one time with +=:
scala> states += ("AR" -> "Arkansas", "AZ" -> "Arizona")
res1: scala.collection.mutable.Map[String,String] =
Map(AL -> Alabama, AR -> Arkansas, AK -> Alaska, AZ -> Arizona)Add multiple elements from another collection using ++=:
scala> states ++= List("CA" -> "California", "CO" -> "Colorado")
res2: scala.collection.mutable.Map[String,String] = Map(CO -> Colorado,
AZ -> Arizona, AL -> Alabama, CA -> California, AR -> Arkansas,
AK -> Alaska)Remove a single element from a map by specifying its key with the
-= method:
scala> states -= "AR"
res3: scala.collection.mutable.Map[String,String] =
Map(AL -> Alabama, AK -> Alaska, AZ -> Arizona)Remove multiple elements by key with the -= or --=
methods:
scala> states -= ("AL", "AZ") res4: scala.collection.mutable.Map[String,String] ...Read now
Unlock full access