Home > front end >  Kotlin - associateBy multiple keys
Kotlin - associateBy multiple keys

Time:12-06

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!

CodePudding user response:

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

Inside flatMap, we associate each of an item's keys to the item. Flattening it creates a List of pairs of key to its Data instance. Then toMap turns that into a Map. If a key appears in more than one Data instance, the last one will "win".

CodePudding user response:

To create a map that associates each key in a Data object with that Data object, you can use the associateBy function. This function takes a transformation function that maps each element in the list to a key-value pair. In this case, you can use a lambda expression that takes a Data object and returns a list of key-value pairs where the keys are the elements of the Data.keys list and the value is the Data object itself. Here is an example:

val map = list.associateBy { data ->
    data.keys.map { key ->
        key to data
    }
}

The resulting map will have the desired structure, with each key in the Data.keys list being associated with the corresponding Data object. Note that this method will only include keys that are unique within the Data objects in the list. If there are multiple Data objects that contain the same key, only the first one will be included in the map.

  • Related