arve
10/18/2018, 8:43 AMdata 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
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 AMval target = mutableMapOf<String, MutableMap<String, MutableList<String>>>()
input.forEach {
target.getOrPut(it.first) { mutableMapOf() }.getOrPut(it.second) { mutableListOf() }.add(it.third)
}