DrJonesYu DrJonesYu - 1 year ago 107
Java Question

In Scala, create a nested HashMap of length N given a list of length N

How can I create a nested hashmap given a list of values?

List(1,2,3,4).toMap => Map(1 -> Map(2 -> Map(3 -> 4)))

After that, how can I merge it with another map?

List(1,2,3,4).toMap => Map(1 -> Map(2 -> Map(3 -> 4)))
List(1,2,3,5).toMap => Map(1 -> Map(2 -> Map(3 -> 5)))
Map(1 -> Map(2 -> Map(3 -> List(4,5)))

I basically want to perform

List(List(1,2,3,8), List(2,3,7,9)).groupBy(x => x(0)).
groupBy(x => x(1)).

Where N is the length of the values within the inner lists.

Answer Source

We can achieve something close to your 1st request without too much difficulty.

scala> List(1,2,3,4).foldRight(Map[Int,Map[Int,_]]()){case (a,b) => Map(a->b)}
res0: scala.collection.immutable.Map[Int,scala.collection.immutable.Map[Int, _]] 
     = Map(1 -> Map(2 -> Map(3 -> Map(4 -> Map()))))

But I don't think there's enough information to fully comprehend your 2nd request. For example: How would the following lists be merged?



From your comments it sounds like maybe the best approach might be to merge the lists before the nesting. This could be done a number of different ways, depending on your requirements.

For example: If order is important (and it looks like it is) can the list be easily sorted? If your using Int then that's trivial.

def nest[A](input: List[A]): Map[A, Map[A,_]] =
  input.foldRight(Map[A,Map[A,_]]()){case (a,b) => Map(a->b)}

val lst1 = List(1,2,3,8)
val lst2 = List(2,3,7,9)
nest( (lst1 ++ lst2).distinct.sorted )
//result: Map(1 -> Map(2 -> Map(3 -> Map(7 -> Map(8 -> Map(9 -> Map()))))))

But I suspect that these simple minded examples might be drifting away from your real-world use cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download