我正在为带有mergeFunction
参数的Java流收集器Collectors.toMap
寻找Kotlin
类似物。
例如,在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) }
)
)
}
有没有类似行为的科特林收藏家?
在这种特殊情况下,计算字符数的最简单方法是:
val charsMap = s.groupingBy { it }.eachCount()
在更通用的方式中,groupingBy
是一个功能强大的工具,可以替代toMap
收集器。