v Mutable Maps - Scala

Mutable Maps

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

Create A Mutable Map

val army = collection.mutable.Map(
    "Tank" -> "A-1 Abrams",
    "Aircraft" -> "F35",
    "Ship" -> "Nimitz Class"

Add An Element

// Add an element
army += ("APC" -> "Bradley IFC")

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

Add Multiple Elements

// Add two elements
army += ("Helicopter" -> "Apache", "Missile" -> "Sidewinder")
Map(Weapon -> M60, APC -> Bradley IFC, Missile -> Sidewinder, Tank -> A-1 Abrams, Aircraft -> F35, Helicopter -> Apache, Ship -> Nimitz Class)

Remove An Element

// Remove an element
army -= "Ship"

// Remove an element (alternative)
Some(A-1 Abrams)

Change A Value

// Change the value of an element
army("Tank") = "Tiger Tank"

Filter A Map

// Keep only the key, value pairs that meet the criteria
army.retain((k,v) => k == "Tank")
Map(Tank -> Tiger Tank)