如何从seq创建不可变的地图/集?

时间:2010-01-01 13:22:01

标签: scala immutability

我尝试从Seq构造不可变集/映射。我目前正在做以下事情:

val input: Seq[(String, Object)] = //.....
Map[String, Object]() ++ input

和套装

val input: Seq[String] = //.....
Set[String]() ++ input

这似乎有点令人费解,有更好的方法吗?

2 个答案:

答案 0 :(得分:27)

在Scala 2.8中:

Welcome to Scala version 2.8.0.r20327-b20091230020149 (Java HotSpot(TM) Client VM, Java 1.6.
Type in expressions to have them evaluated.
Type :help for more information.

scala> val seq: Seq[(String,Object)] = ("a","A")::("b","B")::Nil
seq: Seq[(String, java.lang.Object)] = List((a,A), (b,B))

scala> val map = Map(seq: _*)
map: scala.collection.immutable.Map[String,java.lang.Object] = Map(a -> A, b -> B)

scala> val set = Set(seq: _*)
set: scala.collection.immutable.Set[(String, java.lang.Object)] = Set((a,A), (b,B))

scala>

修改2010.1.12

我发现有一种更简单的方法来创建集合。

scala> val seq: Seq[(String,Object)] = ("a","A")::("b","B")::Nil
seq: Seq[(String, java.lang.Object)] = List((a,A), (b,B))

scala> val set = seq.toSet
set: scala.collection.immutable.Set[(String, java.lang.Object)] = Set((a,A), (b,B))

答案 1 :(得分:16)

要将Seq转换为Map,只需致电toMap上的Seq即可。请注意,Seq的元素必须为Tuple2,即。 (X,Y)(X->Y)

scala> val seq: Seq[(String,String)] = ("A","a")::("B","b")::("C","c")::Nil
seq: Seq[(java.lang.String, java.lang.String)] = List((A,a), (B,b), (C,c))

scala> seq.toMap
res0: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map((A,a), (B,b), (C,c))

要将Seq转换为Set,只需致电toSet上的Seq

scala> val seq: Seq[String] = "a"::"b"::"c"::Nil
seq: Seq[java.lang.String] = List(a, b, c)

scala> seq.toSet
res1: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c)