11.14. Adding, Updating, and Removing Elements with a Mutable Map
Problem
You want to add, remove, or update elements in a mutable map.
Solution
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] ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.