简体   繁体   中英

Scala populate map with random values

I need to create a test for various collections based on Map and 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. so protocode would be:

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?

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

You can use List.fill to create a List of couple (String, String) and then call .toMap on it:

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:

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,

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM