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

使用Java Stream API取频率最高、同频时取最大数值的实现问题

问题分析

你现有代码存在两个问题:

  • 多余的filter(k -> k.getValue() > 1)逻辑:如果流中所有元素出现次数都为1,该过滤会把所有统计项剔除,最终返回空结果,不符合通用逻辑
  • 比较器规则不完整:仅按出现频率排序,没有处理频率相同场景下的数值排序规则,导致同频率时返回结果不符合预期
修正后代码

按照你提出的「优先按出现频率降序,频率相同按数值排序」的规则,可根据实际排序需求选择对应代码:

规则1:频率相同取数值最大

import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// 核心逻辑
Optional<Integer> targetNum = stream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet()
        .stream()
        .max(Comparator.<Map.Entry<Integer, Long>>comparingLong(Map.Entry::getValue)
                .thenComparingInt(Map.Entry::getKey)
                .reversed())
        .map(Map.Entry::getKey);

规则2:频率相同取数值最小(匹配你第二个场景给出的预期结果2)

Optional<Integer> targetNum = stream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet()
        .stream()
        .max(Comparator.comparingLong(Map.Entry<Integer, Long>::getValue)
                .reversed()
                .thenComparingInt(Map.Entry::getKey))
        .map(Map.Entry::getKey);
效果验证
  • 测试第一个流Stream.of(2, 1, 3, 4, 2, 3, 2):2出现3次为最高频率,两种规则返回结果均为2,符合预期
  • 测试第二个流Stream.of(2, 1, 3, 4, 2, 3):2和3出现频率均为2,规则1返回3,规则2返回2,可根据实际需求选择

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:04