Created
August 21, 2011 03:02
-
-
Save jbrechtel/1160045 to your computer and use it in GitHub Desktop.
Scala maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 { keyAndValue => | |
val (key, value) = keyAndValue | |
(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") | |
val newHusbandsAndWives = husbandsAndWives("ram") = "mani" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment