Reputation: 3059
groupBy transforms a list to a map:
Map<K, List<V>>
in a such manner:
val words = listOf("a", "abc", "ab", "def", "abcd")
val byLength = words.groupBy { it.length }
println(byLength.keys) // [1, 3, 2, 4]
println(byLength.values) // [[a], [abc, def], [ab], [abcd]]
I wanna get a Map<K, V> - the same, but values are reduced to a single value, let's say get the first element from the values list:
println(byLength.values) // [a, abc, ab, abcd]
what is the easiest way to get it? Can groupBy provide it by using 2nd parameter? Or need transform Map<K, List> further to Map<K, V>?
Upvotes: 0
Views: 146
Reputation: 31
If the last element that matches your keySselector can be the value
words.associateBy { it.length } //[a, def, ab, abcd]
If you want the first element that matches your selector you can still use groupBy
words.groupBy { it.length }.mapValues { it.value.first() } //[a, abc, ab, abcd]
Upvotes: 0
Reputation: 3747
You don't need groupBy, you can simply write :
words.map { it.length to it }.toMap()
you are creating map entries from list and then creating map from these entries
Upvotes: 1