Kotlin-按多个键关联

vpfxa7rd  于 2022-12-13  发布在  Kotlin
关注(0)|答案(1)|浏览(178)

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!

dsekswqp

dsekswqp1#

val result = list
    .flatMap { data -> data.keys.map { it to data } }
    .toMap()

flatMap中,我们将一个项的每个键与该项相关联。将其扁平化,创建一个与其Data示例相关联的键对列表。然后toMap将其转换为一个Map。如果一个键出现在多个Data示例中,则最后一个将“获胜”。

相关问题