CLOVIS
03/19/2025, 11:01 AMList to a Map but where each initial element that lead to multiple keys?
class A
class B
data class C(
val a: List<A>,
val b: B,
)
val input: List<C> = …
val output: Map<A, List<B>> = input.???
There is .groupBy which does the opposite (each item can create multiple values), but I'm searching for the case where each item can be put into the list in different places.
I guess I can do
val output: Map<A, List<B>> = input.fold(HashMap<A, ArrayList<B>>()) { acc, it ->
for (a in it.a) {
acc.merge(a, arrayListOf(it)) { a, b -> a.addAll(b); a }
}
acc
}
but that's not very elegantSam
03/19/2025, 11:11 AMList<C> into a list of individual key-value pairs:
val pairs = input.flatMap { (aa, b) -> aa.map { a -> a to b } }
val output = pairs.groupBy({ it.first }, { it.second })
I'm not sure it's clearer than what you already had, though...Youssef Shoaib [MOD]
03/19/2025, 11:16 AMbuildMap call, I think it'll be clear enoughphldavies
03/19/2025, 11:31 AMval output: Map<A, List<B>> = buildMap<A, MutableList<B>> {
for((aa, b) in input) {
for(a in aa) {
getOrPut(a, { mutableListOf<B>() }).add(b)
}
}
}
fairly clear of intent