You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对Map<Int, Int>按值降序再按键升序获取最高频次最小数字

Kotlin 实现代码

推荐直接用maxWith配合比较器实现,不需要对全量元素排序,性能更优:

// 示例统计Map
val countMap = mapOf(6 to 2, 4 to 4, 2 to 1, 3 to 4, 1 to 2)

val targetNumber = countMap.maxWith(
    // 第一优先级:按出现次数倒序,次数越高越靠前
    compareByDescending<Map.Entry<Int, Int>> { it.value }
        // 第二优先级:次数相同时按数字大小正序,数值越小越靠前
        .thenBy { it.key }
).key

// 示例输出结果为 3
println(targetNumber)

如果要按你提到的sorted类方法实现也可以,逻辑一致:

val targetNumber = countMap.toList()
    .sortedWith(
        compareByDescending<Pair<Int, Int>> { it.second }
            .thenBy { it.first }
    )
    .first()
    .first

注意事项

如果存在Map为空的场景,建议替换为maxWithOrNull方法,避免抛出NoSuchElementException异常。

内容的提问来源于stack exchange,提问作者MikleRe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:18:00