Trying to convert a table structure into a hierarc...
# codereview
a
Trying to convert a table structure into a hierarchy. Given the following code
Copy code
data class Record(val first: String, val second: String, val third: String)

val input = listOf(
        Record("a", "aa", "aaa"),
        Record("a", "aa", "aab"),
        Record("a", "ab", "aba"),
        Record("b", "ba", "baa"),
        Record("b", "ba", "bab"),
        Record("b", "bb", "bba"),
        Record("b", "bb", "bbb")
)

val expected = mapOf(
        "a" to mapOf(
                "aa" to listOf("aaa", "aab"),
                "ab" to listOf("aba")
        ),
        "b" to mapOf(
                "ba" to listOf("baa", "bab"),
                "bb" to listOf("bba", "bbb")
        )
)
How would you approach it? Currently I'm doing
Copy code
input.groupBy({ it.first })
        .mapValues {
            it.value.groupBy({ it.second }, { it.third })
        }
, but nesting the `groupBy`s feels less than ideal, especially if you consider more than 2 levels.. Any suggestions for better approaches?
j
I don't think it's any better than what you have, but this would also work:
Copy code
val target = mutableMapOf<String, MutableMap<String, MutableList<String>>>()
    input.forEach {
        target.getOrPut(it.first) { mutableMapOf() }.getOrPut(it.second) { mutableListOf() }.add(it.third)
    }