Kotlin toMap collector with duplicate keys

Viewed 1084

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<Character, Integer> charsMap = s2.chars()
            .mapToObj(c -> (char) c)
            .collect(Collectors.toMap(Function.identity(), s -> 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<Char, Int> {
    return word.chars()
        .mapToObj { it.toChar() }
        .collect(
            Collectors.toMap(
                Function.identity(),
                Function { 1 },
                BinaryOperator { a: Int, b: Int -> Integer.sum(a, b) }
            )
        )
}

Is there a Kotlin collector with similar behaviour?

1 Answers

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.

Related