Title: Mutable Maps
Slug: mutable_maps
Summary: Mutable Maps Using Scala.
Date: 2017-04-03 12:00
Category: Scala
Tags: Basics
Authors: Chris Albon

If you want to learn more, check out Scala Cookbook and Programming in Scala.

Create A Mutable Map


In [14]:
val army = collection.mutable.Map(
    "Tank" -> "A-1 Abrams",
    "Aircraft" -> "F35",
    "Ship" -> "Nimitz Class"
)

Add An Element


In [15]:
// Add an element
army += ("APC" -> "Bradley IFC")

// Add an element (alternative)
army.put("Weapon", "M60")


Out[15]:
None

Add Multiple Elements


In [16]:
// Add two elements
army += ("Helicopter" -> "Apache", "Missile" -> "Sidewinder")


Out[16]:
Map(Weapon -> M60, APC -> Bradley IFC, Missile -> Sidewinder, Tank -> A-1 Abrams, Aircraft -> F35, Helicopter -> Apache, Ship -> Nimitz Class)

Remove An Element


In [17]:
// Remove an element
army -= "Ship"

// Remove an element (alternative)
army.remove("Tank")


Out[17]:
Some(A-1 Abrams)

Change A Value


In [18]:
// Change the value of an element
army("Tank") = "Tiger Tank"

Filter A Map


In [19]:
// Keep only the key, value pairs that meet the criteria
army.retain((k,v) => k == "Tank")


Out[19]:
Map(Tank -> Tiger Tank)