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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With