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

Java中对Map执行流操作时如何对value做除法后再排序?

问题分析

你现有代码存在3个核心错误,无法实现需求:

  • Map.Entry.setValue()的返回值是被覆盖的旧值而非修改后的Entry实例,map操作后流内元素类型会从Entry变成Integer,直接导致后续排序、收集逻辑报错
  • 直接对Integer类型做除法默认是整数截断,没有完成转Double再计算的要求
  • 最终存储除法结果的Map泛型错误,你需要的是Map<String, Double>而非Map<String, Integer>

正确实现代码

// 注意X如果可能为0请提前做参数校验避免ArithmeticException
Map<String, Double> result = countMapper.entrySet().stream()
        // 生成新的Entry,提前完成Double类型转换和除法计算,无副作用不修改原Map
        .map(entry -> new AbstractMap.SimpleEntry<>(
                entry.getKey(),
                entry.getValue().doubleValue() / X
        ))
        // 按计算后的Double值倒序排序
        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        // 收集为保持插入顺序的LinkedHashMap
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldVal, newVal) -> oldVal,
                LinkedHashMap::new
        ));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:54:04