Lumos
Lumos

Reputation: 67

Create nested Java TreeMap in Scala

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?

Upvotes: 0

Views: 134

Answers (3)

Johny T Koshy
Johny T Koshy

Reputation: 3887

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
}

Upvotes: 1

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

Upvotes: 2

Brian
Brian

Reputation: 20285

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

Upvotes: 2

Related Questions