Java 8 stream.collect(Collectors.toMap()) analog in kotlin
Assuming that you have
val list: List<Person> = listOf(Person("Ann", 19), Person("John", 23))
the associateBy
function would probably satisfy you:
val map = list.associateBy({ it.name }, { it.age })
/* Contains:
* "Ann" -> 19
* "John" -> 23
*/
As said in KDoc, associateBy
:
Returns a
Map
containing the values provided byvalueTransform
and indexed bykeySelector
functions applied to elements of the given array.If any two elements would have the same key returned by
keySelector
the last one gets added to the map.The returned map preserves the entry iteration order of the original array.
It's applicable to any Iterable
.