I want to create a nested tree map in Scala from 2 lists Eg
private val a = List(0, 100000, 500000, 1000000)
private val b = List (0, 5, 25, 50)
I want the nested tree map to contain keys as the values from list a. The value for these keys would be another tree map that contains keys as the values from list b with values as a default value. To clarify, here's the format in which i want the tree map-default value being 0.:
{
0:{
0:0,
5:0,
25:0,
50:0
},
100000:{
0:0,
5:0,
25:0,
50:0
},
..}
Is there an efficient way to do this in Scala?
CodePudding user response:
Here's an approach to get it into the requested shape. There may be more efficient ways to do this for a large data set.
a.flatMap(aa => TreeMap(aa -> b.flatMap(bb => TreeMap(bb -> 0)).toMap))
val res50: List[(Int, Map[Int, Int])] =
List(
(0, Map(0 -> 0, 5 -> 0, 25 -> 0, 50 -> 0)),
(100000, Map(0 -> 0, 5 -> 0, 25 -> 0, 50 -> 0)),
(500000, Map(0 -> 0, 5 -> 0, 25 -> 0, 50 -> 0)),
(1000000,Map(0 -> 0, 5 -> 0, 25 -> 0, 50 -> 0))
)
CodePudding user response:
All you need to do is:
a.iterator.map { aa =>
aa -> b.iterator.map(bb => bb -> 0).to(TreeMap)
}.to(TreeMap)