Wednesday, 11 June 2014

Scala Collections

Great, I have just been overthinking myself.

I have the following setup:
val nums = List(('a', 2), ('b', 2))
I wanted to convert this List of Tupels into a Map of the kind Map( a -> 2, b -> 2). So, off I went...
val mapping1 = nums groupBy (_._1)    // mapping1  : Map[Char,List[(Char, Int)]] = 
                                      //    Map(b -> List((b,2)), a -> List((a,2)))
val mapping2 = => (x._1, x._2.head._2))
                                      // mapping2  : Map[Char,Int] = Map(b -> 2, a -> 2)
Well, this is hardly convenient.

If you have a Tupel in Scala, like val t = (5, 2), you can access both values using the syntax t._1 and t._2.

Here are the steps:
  • groupBy makes a Map, where the key is the first Value in the tupel, with the original tupel assigned as the value.
  • then the mapping, it takes each item from the map and transforms them to something else. In our case, it transforms (a, List((a, x))) into (a, x) by:
    • leaves the first value of the tupel unchanged, i.e. a
    • takes the head of the List((a, x)), i.e. (a, x)
    • grab the second value from the tupel (a, x), i.e. x
Well, to make a long story short, it seems I could have simply sufficed with:
nums.toMap     //> res6: scala.collection.immutable.Map[Char,Int] = Map(a -> 2, b -> 2)