How to collect items in a list of maps in Scala

327 views Asked by At

If I have a sequence of maps with repeating values and sub maps that look like this:

val from = Seq(
    Map("aaa" -> Map("bbb" -> Map("ccc" -> List(1)))),
    Map("aaa" -> Map("bbb" -> Map("ddd" -> List("a","b")))),
    Map("aaa" -> Map("bbb" -> Map("eee" -> List(99,100)))),
    Map("aaa" -> Map("bbb" -> Map("ccc" -> List(2,3)))),
    Map("aaa" -> Map("bbb" -> Map("ddd" -> List("c","d")))),
    Map("aaa" -> Map("bbb" -> Map("eee" -> List(101,102)))),
    Map("aaa" -> Map("bbb" -> Map("ccc" -> Map("ddd" -> Map("eee" -> Map("fff" -> Map("ggg" -> List(true, false)))
    ))))))

What is the Scala way to converting it into a collated structure that looks like this:

val to = Seq(
    Map("aaa" ->
      Map("bbb" -> Map(
        "ccc" -> List(1, 2, 3),
        "ddd" -> List("a", "b", "c", "d"),
        "eee" -> List(99, 100, 101, 102),
        "fff" -> 
            Map("ggg" -> List(true, false))
      )
    )
  )
)
1

There are 1 answers

4
Arseniy Zhizhelev On

This structure is called Trie or "prefix tree". There is a gist on github (https://gist.github.com/timcowlishaw/1363652) that implements the concept.

Updated

The actual conversion algorithm necessarily (IMHO) converts the nested maps back to key strings. And then the construction of Trie is as simple as putting all elements with put in the provided gist. So I think it's better to use the structure a bit earlier in the program.