gpt4 book ai didi

kotlin - Kotlin FP:将List 转换为Map

转载 作者:行者123 更新时间:2023-12-02 13:03:13 24 4
gpt4 key购买 nike

我有一个字符串列表,我想转换为出现的 map 。 (〜映射值是字符串在列表中重复多次的计数)

命令式的方式如下

fun transformMap(list: List<String>): Map<String, Int> {
val map = mutableMapOf<String,Int>()
for(n in list){
map.put(n,map.getOrDefault(n,0) + 1)
}
return map.toMap()
}

如何以函数式编程方式编写此代码?

在Java 8+中,将这样编写
String[] note;
Map<String, Integer> noteMap = Arrays.stream(note)
.collect(groupingBy(Function.identity(),
collectingAndThen(counting(), Long::intValue)));

最佳答案

您可以通过Grouping扩展名使用Kotlin的 Iterable<T>.groupingBy 在一行中完成此操作:

val myList = listOf("a", "b", "c", "a", "b", "a")
val myMap = myList.groupingBy { it }.eachCount()

println(myMap)
// Prints {a=3, b=2, c=1}

关于kotlin - Kotlin FP:将List <String>转换为Map <String,Int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com