我要找 Kotlin
Java 流收集器的模拟 Collectors.toMap
与 mergeFunction
范围。
例如,在 Java 中,为了计算 String 中的字符数,可以使用以下代码片段:
Map<Character, Integer> charsMap = s2.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toMap(Function.identity(), s -> 1, Integer::sum));
如果我们将 Java 片段转换为 Kotlin,由于显式类型的使用,它看起来相当难看。
private fun countCharsV2(word: String): Map<Char, Int> {
return word.chars()
.mapToObj { it.toChar() }
.collect(
Collectors.toMap(
Function.identity(),
Function { 1 },
BinaryOperator { a: Int, b: Int -> Integer.sum(a, b) }
)
)
}
是否有具有类似行为的 Kotlin 收集器?
最佳答案
在这种特殊情况下,计算 char 的最简单方法是:
val charsMap = s.groupingBy { it }.eachCount()
更一般的时尚
groupingBy
是一个强大的工具,可以替代 toMap
集电极。
关于java - 具有重复键的 Kotlin toMap 收集器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61069505/