04. Maps Tuples - RobertMakyla/scalaWiki GitHub Wiki

Immutable Map

val m = Map( 1->"a" , 2->"b" )     // by default: scala.collection.immutable.Map
val m = Map( (1, "a"), (2, "b") )  // exactly the same

val newM = m + (3 ->  "c")         // m is not changed

val m = new HashMap[Int, String]      // crating new empty and immutable hashmap

Getting values:

m(1)      // "a" - the exact value or exception
m.get(1)  // Some("a") - or None
m.getOrElse(1, -1)      // return type:  Any
m.getOrElse(1, "other") // return type:  String

Mutable Map

val m = scala.collection.mutable.Map(1->"a" , 2->"b" )

Updating MUTABLE maps

m(1) = "a updated" // updating value

m += (1 -> "changed", 4 ->  "added") // changing and adding
          //Map( 1 -> "changed",  2->"b" , 4 -> "added")

m -= 4   // Map( 1 -> "a changed",  2->"b" )
        // if exists - they are removed, If not - no changes

Updating IMMUTABLE or MUTABLE maps

val newM = m + (5 -> "e")   // The 'm' (mutable or not) is not changed
val newM = m - 5            // The 'm' (mutable or not) is not changed

You might think that it is inefficient to keep constructing new maps, but that is not the case. The old and new maps share most of their structure. This is possible because they are immutable.

Iterating

for ((k, v) <- m) println( k + " - " + v ) // printing

for ((k, v) <- m) yield (v, k)   // reversing

Key set

for(k <- m.keySet) println(k) // keys: Set[String]

for((k,v) <- m) println(k)

Values

for (v <- m.values) println(v)  // values: Iterable[Int]
for((k,v) <- m) println(v)

Tree Map - to get immutable tree map, in scala we have SortedMap

val scores = scala.collection.immutable.SortedMap("A" -> 1, "C" -> 3, "B" -> 2)

Unfortunately as of scala 2.9 there is no mutable tree map. I will need to use java TreeMap (chapter 13))

LinkedHashMap

Used to keep values in inserting order - because normal Map doesn't necessarily

val months = scala.collection.mutable.LinkedHashMap("Jan" -> 1,  "Feb" -> 2, "Mar" -> 3 )

Tuples

val t                               = (1, 3.14, "Fred")
val t : Tuple3[Int, Double, String] = (1, 3.14, "Fred")  // the same

Values from Tuples

 t._3    // "Fred"   cause indexing is 1-3  (not 0-2)
 t _3    // the same

BEST PRACTICE - Pattern Matching when accessing tuples

val (first, second, third) = t   // first = 1 
                                 // second = 3.14 
                                 // third = "Fred"

val (_, second, _) = t   // just second = 3.14

Partition - returns Tuple (interview)

val t = "New York".partition(_.isUpper)         // ("NY", "ew ork")
val (up, low) = "New York".partition(_.isUpper) // up = "NY" 
                                                // low = "ew ork"

List(1,2,3,4,5) partition( _ > 3)  // (List(4, 5),List(1, 2, 3))

Zipping - returns array/vector of Tuples (interview)

val symbols = Array("<", "-", ">")
val counts = Array(2, 10, 2)
val pairs = symbols.zip(counts)    // Array( (<,2), (-,10), (>,2) )

for ((s, n) <- pairs) print(s * n) // <<---------->>

"ab".zip("12")   // Vector((a,1), (b,2))

*Interoperability with Java

Java -> scala

import scala.collection.JavaConversions.mapAsScalaMap
val scores: scala.collection.mutable.Map[String, Int] = new java.util.TreeMap[String, Int]

java properties -> scala

import scala.collection.JavaConversions.propertiesAsScalaMap
val props: scala.collection.Map[String, String] = System.getProperties()
⚠️ **GitHub.com Fallback** ⚠️