我如何在Scala中生成一个immutable.Map?

时间:2010-05-04 07:36:25

标签: scala map for-loop immutability yield

我试过这个,但它不起作用:

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

我如何将Tuple2s列表转换为Map?

4 个答案:

答案 0 :(得分:14)

这简直太简单了:

Map(listOf2Tuples: _*)

使用Map随播广告对象中的apply方法。

答案 1 :(得分:10)

我的第一次尝试是这样的:

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)

但这是最好的解决方案:

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

需要:_*来为编译器提供一个提示,将列表用作varargs参数。否则会给你:

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

从Scala 2.8开始,您可以使用toMap

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))

答案 2 :(得分:9)

在2.8中,您可以使用toMap方法:

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))

这适用于任何对的集合。请注意,文档中有关于其重复策略的说法:

  

重复的密钥将被覆盖   以后的密钥:如果这是一个无序的   集合,哪个关键在   生成的地图未定义。

答案 3 :(得分:7)

在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>