简体   繁体   English

如何获取地图<K, V>来自 groupBy 而不是 Map <K, List<V> &gt;?

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

groupBy transforms a list to a map: groupBy 将列表转换为地图:

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:我想要一个 Map<K, V> - 相同,但值减少为单个值,假设从值列表中获取第一个元素:

println(byLength.values) // [a, abc, ab, abcd]

what is the easiest way to get it?获得它的最简单方法是什么? Can groupBy provide it by using 2nd parameter? groupBy 可以使用第二个参数提供它吗? Or need transform Map<K, List> further to Map<K, V>?或者需要将 Map<K, List> 进一步转换为 Map<K, V>?

You don't need groupBy, you can simply write :你不需要 groupBy,你可以简单地写:

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如果与您的 keySselector 匹配的最后一个元素可以是值

words.associateBy { it.length }  //[a, def, ab, abcd]

If you want the first element that matches your selector you can still use groupBy如果您想要与选择器匹配的第一个元素,您仍然可以使用 groupBy

words.groupBy { it.length }.mapValues { it.value.first() }  //[a, abc, ab, abcd]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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