[英]Scala populate map with random values
I need to create a test for various collections based on Map and HashMap. 我需要为基于Map和HashMap的各种集合创建测试。
I have two functions that create test data, eg: 我有两个创建测试数据的函数,例如:
def f1: String = { ... )
def f2: String = { ... }
these functions create random data every time they are called. 这些函数在每次调用时都会创建随机数据。
My map is: 我的地图是:
val m:Map[String,String] = ...
what I try to accomplish is construct an immutable map with 10000 random items that were generated by calling f1/f2. 我试图完成的工作是构造一个具有10000个随机项的不可变映射,这些随机项是通过调用f1 / f2生成的。 so protocode would be:
所以protocode将是:
for 1 to 10000
add-key-value-to-map (key = f1(), value = f2() )
end for
how can I accomplish this in scala, without destroying and rebuilding the list 10000 times? 如何在scala中完成此操作,而又不破坏并重建列表10000次?
EDIT: Since it wasn't clear in the original post above, I am trying to run this with various types of maps (Map, HashMap, TreeMap). 编辑:由于上面的原始帖子中不清楚,我试图用各种类型的地图(Map,HashMap,TreeMap)运行它。
You can use List.fill
to create a List of couple (String, String)
and then call .toMap
on it: 您可以使用
List.fill
来创建一对夫妇(String, String)
的列表,然后在其上调用.toMap
:
scala> def f1 = util.Random.alphanumeric take 5 mkString
f1: String
scala> def f2 = util.Random.alphanumeric take 5 mkString
f2: String
scala> val m = List.fill(5)(f1 -> f2).toMap
m: scala.collection.immutable.Map[String,String] =
Map(T7hD8 -> BpAa1, uVpno -> 6sMjc, wdaRP -> XSC1V, ZGlC0 -> aTwBo, SjfOr -> hdzIN)
Alternatively you could use Map
/ HashMap
/ TreeMap
's .apply
function: 或者,您可以使用
Map
/ HashMap
/ TreeMap
的.apply
函数:
scala> val m = collection.immutable.TreeMap(List.fill(5)(f1 -> f2) : _*)
m: scala.collection.immutable.TreeMap[String,String] =
Map(3cieU -> iy0KV, 8oUb1 -> YY6NC, 95ol4 -> Sf9qp, GhXWX -> 8U8wt, ZD8Px -> STMOC)
List.fill(10000)((f1, f2)).toMap
val m = (1 to 10000).foldLeft(Map.empty[String,String]) { (m, _) => m + (f1 -> f2) }
Using tabulate
as follows, 使用以下
tabulate
,
Seq.tabulate(10000)(_ => f1 -> f2).toMap
It proves unclear whether the random key generator function may duplicate some keys, in which case 10000
iterations would not suffice to produce a map of such size. 尚不清楚随机密钥生成器功能是否可以复制某些密钥,在这种情况下,
10000
次迭代不足以生成这种大小的映射。
An intuitive approach, 直观的方法
(1 to 10000).map(_ => f1 -> f2).toMap
Using a recursive function instead of generating a range to iterate over, (although numerous intermediate Maps are created), 使用递归函数而不是生成要迭代的范围(尽管创建了大量中间图),
def g(i: Int): Map[String,String] = {
if (i<=0)
Map()
else
Map(f1 -> f2) ++ g(i-1)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.