Scala:如何从Set [K]和从K到V的函数创建一个Map [K,V]? [英] Scala: How to create a Map[K,V] from a Set[K] and a function from K to V?
问题描述
从 Set [K]
创建 Map [K,V]
的最佳方式是函数从 K
到 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
$ $ p $ val func2 =(r:Map [Int,String],i:Int)=> (func2)
由于 foldLeft
构造了 Map
,所以这将比Jesper的解决方案执行得更好。在一次通过。 Jesper的代码首先创建一个中间数据结构,然后需要将其转换为最终的 Map
。
更新:我编写了一个微基准,测试每个答案的速度:
Jesper(原始):35s 738ms
Jesper(改进):11s 618ms
dbyrne:11s 906ms
Rex Kerr: 12s 206ms
Eastsun:11s 988ms
看起来他们几乎与长时间相同因为您避免构建中间数据结构。
What is the best way to create a Map[K,V]
from a Set[K]
and function from K
to V
?
For example, suppose I have
scala> val s = Set(2, 3, 5)
s: scala.collection.immutable.Set[Int] = Set(2, 3, 5)
and
scala> def func(i: Int) = "" + i + i
func: (i: Int)java.lang.String
What is the easiest way of creating a Map[Int, String](2 -> "22", 3 -> "33", 5 -> "55")
You can use foldLeft
:
val func2 = (r: Map[Int,String], i: Int) => r + (i -> func(i))
s.foldLeft(Map.empty[Int,String])(func2)
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]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!