Java 8 stream.collect (Collectors.toMap ()) counterpart in kotlin

Suppose I have a list of people and would like to have Map<String, Person>where String is the name of the person. How do I do this in Kotlin?

+4
source share
1 answer

Assuming you have

val list: List<Person> = listOf(Person("Ann", 19), Person("John", 23))

the function associateBywill probably satisfy you:

val map = list.associateBy({ it.name }, { it.age })
/* Contains:
 * "Ann" -> 19
 * "John" -> 23
*/

As stated in KDoc associateBy:

Returns a Mapcontaining the values ​​provided valueTransformand indexed by the functions keySelectorapplied to the elements of this array.

If any two elements have the same key returned keySelector, the last one is added to the map.

The returned mapping preserves the iteration order of the record in the source array.

Iterable.

+9

All Articles