Hello, I’m trying to understand some Kotlin data mapping functions (which are a lot of them and there is a need to read a separate book). The case is next: I need to flat List<HashMap<String, List<String>>>
and merge all the values. So, I found a solution:
@Test
fun foldMap() {
val list = listOf(
hashMapOf("A" to listOf("a1", "a2"), "B" to listOf("b1", "b2")),
hashMapOf("A" to listOf("a11", "a21"), "C" to listOf("c11", "c21")),
hashMapOf("C" to listOf("c12", "c22"))
)
val map = list.fold(hashMapOf<String, List<String>>()) { acc, curr ->
curr.forEach { entry ->
acc.merge(entry.key, entry.value) { new, old -> new + old }
}
acc
}
assertEquals("{A=[a1, a2, a11, a21], B=[b1, b2], C=[c11, c21, c12, c22]}", map.toString())
}
Can the map
calculation be shorter?