Hi I am having a map like this: [ key1 : [1,2,3],...
# announcements
j
Hi I am having a map like this: [ key1 : [1,2,3], key2: [2,3,4], key3: [3,4,5]] I would like to get a map like this: [1[key1],2[key1,key2],3[key1,key2,key3],4[key2,key3],5:[key3]] any suggestions on how to group by elements in a list and not the list itself? Thanks
l
Are you look for something like this ?
Copy code
map.entries.associateBy({ it.value }) { it.key }
j
no this print:
Copy code
{[1, 2, 3]=key1, [2, 3, 4]=key2, [3, 4, 5]=key3}
I want to have a map where I have each one of the single item in the values in the original map mapped to a list of keys where is appear
Copy code
fun main() {
    val x = mapOf("key1" to listOf(1, 2, 3), "key2" to listOf(2, 3, 4), "key3" to listOf(3, 4, 5))

    val y = x.entries.associateBy({ it.value }) { it.key }
    println(y)
}
l
I think this does what you want but maybe there is better way 😅
Copy code
x.entries.flatMap { e -> e.value.map { it to e.key } }.groupBy  ( { it.first }, { it.second })
j
Thanks @Lidonis Calhau it works 👑
🎉 1
p
This solution should be more efficient because it doesn't create the intermediate list
Copy code
val y = mutableMapOf<Int, MutableList<String>>()
x.entries.forEach { e -> e.value.forEach { y.getOrPut(it) { mutableListOf() }.add(e.key) } }
j
Thanks @Pedro Pereira will check that