Home > Enterprise >  Create nested Java TreeMap in Scala
Create nested Java TreeMap in Scala

Time:12-04

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?

Edit: I want to use the same logic but use a Java Tree Map in Scala instead. Could someone please guide me?

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.canBuildFrom)
}.to(TreeMap.canBuildFrom)

You can see the code running here

CodePudding user response:

And using foldLeft

a.foldLeft(TreeMap.empty[Int, TreeMap[Int, Int]]) { (acc, elem) =>
  acc   (elem -> b.map(bKey => bKey -> 0)
    .to(TreeMap.canBuildFrom)) 
    //.to(TreeMap)) //if you use 2.13
}
  • Related