I have the following list:
val d1 = Data(keys = listOf("a", "b"), ...)
val d2 = Data(keys = listOf("c"), ...)
val list = listOf(d1, d2)
Now I want to transform that list to the following map:
val map = mapOf(
"a" to d1,
"b" to d1,
"c" to d2
)
Keys are unique per Data object.
I want something like associateByAll
that maps multiple keys to the same object:
val map = list.associateByAll { it.keys }
What is best way to do this in Kotlin?
Thanks!
1条答案
按热度按时间dsekswqp1#
在
flatMap
中,我们将一个项的每个键与该项相关联。将其扁平化,创建一个与其Data示例相关联的键对列表。然后toMap
将其转换为一个Map。如果一个键出现在多个Data示例中,则最后一个将“获胜”。