Home > front end >  convert a List of objects to a Map in Kotlin
convert a List of objects to a Map in Kotlin

Time:12-06

What is the most efficient way to convert a List of objects to a Map in Kotlin. Given a list of objects, a map is a structure that allows for efficient retrieval of values associated with a specific key.

CodePudding user response:

The function to do this is actually built in to Kotlin. It's called associateBy.

inline fun <T, K> Iterable<T>.associateBy(
    keySelector: (T) -> K
): Map<K, T>

It takes a single argument, mapping an element of type T to the desired key of type K.

So, if you had a list of Person objects, and each person had a name you wanted to index by, you could write

personList.associateBy { it.name }

to get the map from names to people.

Note that there also exists a more general function called associate, which maps a T to a key and a value (where the value may or may not be equal to the original T value). This is useful if you want to perform a mapping and produce an associative container at the same time. But since it sounds like your use case involves indexing existing objects, associateBy is probably sufficient.

  • Related