# codereview


10/18/2018, 8:43 AM
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?

Joris PZ

10/18/2018, 10:01 AM
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)