Skip to content

Instantly share code, notes, and snippets.

@ketankhairnar
Created March 6, 2011 14:38
Show Gist options
  • Save ketankhairnar/857336 to your computer and use it in GitHub Desktop.
Save ketankhairnar/857336 to your computer and use it in GitHub Desktop.
basic scala map features
object MapTests extends Application {
override def main(args: Array[String]) {
//reference http://www.scala-lang.org/api/current/scala/collection/immutable/Map.html
val worldCupWinners = Map(1975 -> "West Indies",
1979 -> "West Indies",
1983 -> "India",
1987 -> "Australia",
1992 -> "Pakistan",
1996 -> "Sri Lanka",
1999 -> "Australia",
2003 -> "Australia",
2007 -> "Australia")
val evenYears = worldCupWinners filterKeys (_ % 2 == 0)
println("evenYears: " + evenYears)
val ausTotalWins = worldCupWinners.filter {
element =>
val (year, country) = element
country contains "Aus"
}
println("ausTotalWins: " + ausTotalWins)
val countAfter2k = ausTotalWins.filterKeys(_ >= 2000).size
val countBefore2k = ausTotalWins.filterKeys(_ < 2000).size
println("countAfter2k:" + countAfter2k)
println("countBefore2k:" + countBefore2k)
// some and none goodies
println(worldCupWinners.get(1983))
println(worldCupWinners.get(2000))
//scala map is immutable so need to use update for 2011 winner as below
worldCupWinners.updated(2011, "Winner of India vs Pakistan")
// its immutable so it wont add the new value
println(worldCupWinners.mkString(", "))
// another try
val updWorldCupWinners = worldCupWinners.updated(2011, "Winner of India vs Pakistan")
println(updWorldCupWinners.mkString(", "))
//head vs tail
println("head :" + worldCupWinners.head)
println("tail :" + worldCupWinners.tail)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment