J.J. Beam
J.J. Beam

Reputation: 3059

How get Map<K, V> from groupBy instead of Map<K, List<V>>?

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

Answers (2)

John
John

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

Autocrab
Autocrab

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

Related Questions