By Alvin Alexander. Last updated: August 6, 2020
If you ever need to create a large test Scala Map
, I just used this approach and it worked fine:
val map = (for (i <- 1 to 5_000_000) yield (i, 10*i)).toMap
The initial results in the Scala REPL look like this:
val map: Map[Int, Int] = HashMap(4584205 -> 45842050, 2231874 -> 22318740, ...
The code works by creating a series of tuples with the yield expression, where each key is i
, and each value is 10*i
. Here are a couple of other ways to convert a Scala sequence to a map:
val map = Vector.range(0,1_000_000).map(i => (i, i*10)).toMap val map = Vector.range(0,1_000_000).map(i => i -> i*10).toMap
In the map
method of those two examples, I create a Tuple2
from each element in the initial Vector
. The examples show two different ways to create a tuple.
In summary, if you ever need to create a large Scala Map
for testing, I hope these examples are helpful.