我正在编写一个函数,它遍历一个集合,并查找其中最常见的项.
以下是我到目前为止获得的值,并添加它们在集合中出现的次数.我把这个值作为一个键放到一个 map 中,它出现的次数作为它的值.
fun mostCommon(input: Collection<Int>): Set<Int> {
var newMap: MutableMap<Int, Int> = HashMap()
for (item in input) {
if (newMap.containsKey(item)) {
//TODO: add 1 to value if key is found
} else {
newMap.put(item, 1)
}
}
return emptySet()
}
I am having trouble finding a way to add 1 to its value if the key already exists.
I tried doing this:
newMap[item] +=1
But I get an error about plusAssign(1) not being allowed on Nullable receiver.