Skip to content

Instantly share code, notes, and snippets.

@leedm777
Forked from jbrechtel/maps.scala
Created March 13, 2012 14:23
Show Gist options
  • Save leedm777/2029089 to your computer and use it in GitHub Desktop.
Save leedm777/2029089 to your computer and use it in GitHub Desktop.
Scala maps
//create a map
val cars = Map("james" -> "BMW", "ike" -> "Infiniti", "stephen" -> "Buick")
//create a map from an Array
//Scala does not provide a convenience method to do this... :(
val carArray = Array("james", "BMW", "ike", "Infiniti", "stephen", "Buick")
val cars = carArray.grouped(2).toList.map(c => (c.head,c.last)).toMap
//mapping over a map
//transform all string keys to symbols (interned strings)
Map("name" -> "James", "job" -> "consultant", "age" -> "28").map {
case (key, value) =>
(Symbol(key),value)
}
//looking up values in a map
val urls = Map("google" -> "http://google.com", "twitter" -> "http://twitter.com")
println(urls("twitter"))
//add an entry to an immutable map
val husbandsAndWives = Map("james" -> "ashley", "pat" -> "lauren", "david" -> "jenny")
val newHusbandsAndWives = husbandsAndWives.updated("ram", "mani")
//add an entry to a mutable map
import collection.mutable
val husbandsAndWives = mutable.Map("james" -> "ashley", "pat" -> "lauren", "david" -> "jenny")
husbandsAndWives("ram") = "mani"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment