Kotlin toMap收集器与重复键

huangapple go评论66阅读模式
英文:

Kotlin toMap collector with duplicate keys

问题

我正在寻找适用于 Kotlin 的 Java 流收集器 Collectors.toMap 的类似物,其中包含 mergeFunction 参数。

例如,在 Java 中,为了计算字符串中的字符数,可以使用以下代码片段:

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 收集器?

英文:

I'm looking for Kotlin analogue for Java stream collector Collectors.toMap with mergeFunction parameter.

For instance, in Java in order to count chars in String it's possible to use the following code snippet:

Map&lt;Character, Integer&gt; charsMap = s2.chars()
            .mapToObj(c -&gt; (char) c)
            .collect(Collectors.toMap(Function.identity(), s -&gt; 1, Integer::sum));

If we convert the Java snippet to Kotlin it looks rather ugly because of explicit types usage.

private fun countCharsV2(word: String): Map&lt;Char, Int&gt; {
    return word.chars()
        .mapToObj { it.toChar() }
        .collect(
            Collectors.toMap(
                Function.identity(),
                Function { 1 },
                BinaryOperator { a: Int, b: Int -&gt; Integer.sum(a, b) }
            )
        )
}

Is there a Kotlin collector with similar behaviour?

答案1

得分: 1

在这种特殊情况下,计算字符最简单的方法是:

val charsMap = s.groupingBy { it }.eachCount()

更一般的情况下,groupingBy 是一个强大的工具,可作为 toMap 收集器的替代品。

英文:

In this particular case the easiest way to count char is:

val charsMap = s.groupingBy { it }.eachCount()

In more general fashion groupingBy is a powerful tool which works as a replacement to toMap collector.

huangapple
  • 本文由 发表于 2020年4月7日 05:50:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/61069505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定