views:

249

answers:

4

I have tried this but it does not work:

val map:Map[String,String] = for {
    tuple2 <- someList
  } yield tuple2._1 -> tuple2._2

How else would I convert a List of Tuple2s into a Map?

+12  A: 

It couldn't be simpler:

Map(listOf2Tuples: _*)

using the apply method in Map companion object.

Alexey Romanov
Only works if `listOf2Tuples` is explicit and not a variable/val
michael.kebe
Fixed it to work correctly.
Alexey Romanov
+1, This IMO is the best way to do it. :)
missingfaktor
+6  A: 

My First try is this:

scala> val country2capitalList = List("England" -> "London", "Germany" -> "Berlin")
country2capitalList: List[(java.lang.String, java.lang.String)] = List((England,London), (Germany,Berlin))

scala> val country2capitalMap = country2capital.groupBy(e => e._1).map(e => (e._1, e._2(0)._2))
country2capitalMap: scala.collection.Map[java.lang.String,java.lang.String] = Map(England -> London, Germany -> Berlin)

But here is the best solution:

scala> val betterConversion = Map(country2capitalList:_*)
betterConversion: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(England -> London, Germany -> Berlin)

The :_* is needed to give the compiler a hint to use the list as a varargs argument. Otherwise it will give you:

scala> Map(country2capitalList)
<console>:6: error: type mismatch;
 found   : List[(java.lang.String, java.lang.String)]
 required: (?, ?)
       Map(country2capitalList)
           ^
michael.kebe
+6  A: 

In scala 2.8:

scala> import scala.collection.breakOut
import scala.collection.breakOut

scala> val ls = List("a","bb","ccc")
ls: List[java.lang.String] = List(a, bb, ccc)

scala> val map: Map[String,Int] = ls.map{ s => (s,s.length) }(breakOut)
map: Map[String,Int] = Map((a,1), (bb,2), (ccc,3))

scala> val map2: Map[String,Int] = ls.map{ s => (s,s.length) }.toMap
map2: Map[String,Int] = Map((a,1), (bb,2), (ccc,3))

scala>
Eastsun
+2  A: 

In 2.8, you can use the toMap method:

scala> val someList = List((1, "one"), (2, "two"))   
someList: List[(Int, java.lang.String)] = List((1,one), (2,two))

scala> someList.toMap
res0: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,one), (2,two))

This will work for any collection of pairs. Note that the documentation has this to say about its duplicate policy:

Duplicate keys will be overwritten by later keys: if this is an unordered collection, which key is in the resulting map is undefined.

Ben Lings