Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Suppose I have a list of persons and would like to have Map<String, Person>, where String is person name. How should I do that in kotlin?

like image 289
Yurii Avatar asked Jul 12 '15 15:07

Yurii


2 Answers

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 by valueTransform and indexed by keySelector 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.

like image 158
hotkey Avatar answered Sep 23 '22 10:09

hotkey


Many alternatives in Kotlin :)

val x: Map<String, Int> = list.associate { it.name to it.age }
val y: Map<String, Int> = list.map { it.name to it.age }.toMap()
var z: Map<String, Int> = list.associateBy({ it.name }, { it.age })

The best option for this particular case IMO is the first as Lambdas are not needed but simple transformation.

like image 44
Juan Rada Avatar answered Sep 24 '22 10:09

Juan Rada