Kotlin: Find most common element in collection

As you already noticed, the error was related to nullability-handling. I'd suggest a more functional approach without explicit looping but simple grouping:

val numbersByElement = input.groupingBy { it }.eachCount()
//gives something like this {1=3, 2=5, 3=4, 5=2, 4=1}

The result is a Map with the elements from input as its keys and the number of occurrences of the elements as the corresponding values.

You can now find the most common element with maxBy:

numbersByElement.maxBy { it.value }?.key // gives an Int?

Map.get returns an Int?, i.e. if no item is found, null will be returned. You can utilize the elvis operator to deal with that:

val newMap = mutableMapOf<Int, Int>()

for (item in input) {
    newMap[item] = (newMap[item] ?: 0) + 1
}

Another alternative is to use Java 8's Map.merge:

newMap.merge(item, 1) { i, j -> i + j }
// or the equivalent
newMap.merge(item, 1, Int::plus)

This will put 1 in the map, if the key is not present yet, and otherwise apply the lambda to the old and new value, in our case add the old value to the new value and store the result under the key.

Tags:

Hashmap

Kotlin