我正在编写一个函数,它遍历一个集合,并查找其中最常见的项.

以下是我到目前为止获得的值,并添加它们在集合中出现的次数.我把这个值作为一个键放到一个 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.

推荐答案

正如您已经注意到的,该错误与可空性处理有关.我建议采用一种功能性更强的方法,不需要显式循环,只需要简单的分组:

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

结果是一个映射,其中input个元素作为其键,元素的出现次数作为相应的值.

You can now find the most common element with maxBy:

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

Kotlin相关问答推荐

如何使用收件箱文件中的类运行Kotlin应用程序

了解Kotlin函数

如何避免使用公共类实现内部接口

顶级属性的初始化

多次运行espresso测试

为什么 Kotlin 扩展运算符在传递原始可变参数时需要 toTypedArray()?

将 Gradle 子元素与 Kotlin 多平台一起使用

将 Completable 转换为 Single 的规范方法?

Kotlin 中的数据类

如何从 Firestore 查询中排除元素?

Kotlin Compose,在行中对齐元素

未找到导入 kotlinx.coroutines.flow.*

将ExpectedException与Kotlin一起使用

如何在Kotlin中获得KType?

使用导航组件在BottomNavigationView中传递参数

Kotlin:具有多个不同类型设置器的单个属性

修改扩展函数中的this

我应该使用Kotlin数据类作为JPA实体吗?

@StringRes、@DrawableRes、@LayoutRes等android注释使用kotlin参数进行判断

Dagger 2 androidx fragment不兼容类型