2

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))
      )
    )
  )
)
OutNSpace
  • 373
  • 2
  • 8
  • The structure given in the example is bizarre in that every Map as only one entry (which makes the maps overkill, simple pairs would do the job). Is that intended? – Didier Dupont Sep 07 '13 at 22:38
  • The reason there is only one entry per map is because it represents a path to those values. The goal is to collate all the values in the sequence together making paths hierarchical. (In actuality each node might have more than one value mapped onto it.) – OutNSpace Sep 07 '13 at 23:49

1 Answers1

4

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.

Arseniy Zhizhelev
  • 2,381
  • 17
  • 21
  • While that is a useful piece of information, I don't think it answers the question. You provide no method, idiomatic or not, for converting `val from` into a Trie. Nor does the linked package. So while this is a great comment, I don't think it qualifies as an answer. – itsbruce Sep 07 '13 at 20:03
  • Well, I believe that giving the right names to things can greatly simplify solution finding. If OutNSpace didn't call it a Trie then I guess they haven't spot it yet. Armed with the notion OutNSpace will not only solve this particular problem, but also rethink the problem and use the Trie structure earlier in the program. – Arseniy Zhizhelev Sep 07 '13 at 20:15
  • As mentioned, this is useful but does not in fact answer my question. (and there is no possibility to use Trie structure here) – OutNSpace Sep 07 '13 at 20:16
  • I think that `TreeMap` itself should behave as required. – Arseniy Zhizhelev Sep 08 '13 at 13:52