问题描述
从 Set[K]
创建 Map[K,V]
和从 K
到 的函数的最佳方法是什么?代码>V
?
What is the best way to create a Map[K,V]
from a Set[K]
and function from K
to V
?
例如,假设我有
scala> val s = Set(2, 3, 5)
s: scala.collection.immutable.Set[Int] = Set(2, 3, 5)
和
scala> def func(i: Int) = "" + i + i
func: (i: Int)java.lang.String
创建 Map[Int, String](2 -> "22", 3 -> "33", 5 -> "55") 的最简单方法是什么
推荐答案
可以使用foldLeft
:
val func2 = (r: Map[Int,String], i: Int) => r + (i -> func(i))
s.foldLeft(Map.empty[Int,String])(func2)
这将比 Jesper 的解决方案执行得更好,因为 foldLeft
一次性构造了 Map
.Jesper 的代码首先创建了一个中间数据结构,然后需要将其转换为最终的Map
.
This will perform better than Jesper's solution, because foldLeft
constructs the Map
in one pass. Jesper's code creates an intermediate data structure first, which then needs to be converted to the final Map
.
更新:我编写了一个微基准来测试每个答案的速度:>
Update: I wrote a micro benchmark testing the speed of each of the answers:
Jesper (original): 35s 738ms
Jesper (improved): 11s 618ms
dbyrne: 11s 906ms
Rex Kerr: 12s 206ms
Eastsun: 11s 988ms
只要您避免构建中间数据结构,它们看起来都差不多.
Looks like they are all pretty much the same as long as you avoid constructing an intermediate data structure.
这篇关于Scala:如何从 Set[K] 和从 K 到 V 的函数创建 Map[K,V]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!