简体   繁体   中英

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>?

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM