开发者

How would I yield an immutable.Map in Scala?

开发者 https://www.devze.com 2022-12-29 16:09 出处:网络
I have tried this but it does not work: val map:Map[String,String] = for { tuple2 <- someList } yield tuple2._1 -> tuple2._2

I have tried this but it does not work:

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

How else 开发者_Go百科would I convert a List of Tuple2s into a Map?


It couldn't be simpler:

Map(listOf2Tuples: _*)

using the apply method in Map companion object.


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

From Scala 2.8 on you can use 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))


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号