gpt4 book ai didi

scala - 如何从序列创建不可变的映射/集?

转载 作者:行者123 更新时间:2023-12-03 10:12:43 29 4
gpt4 key购买 nike

我尝试从Seq构造不可变的Set / Map。我目前正在执行以下操作:

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

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

这似乎有些令人费解,是否有更好的方法?

最佳答案

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

关于scala - 如何从序列创建不可变的映射/集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1988574/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com