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

如何让Collectors.groupingBy()返回排序后的LinkedHashMap?

解决方案

可以在单次链式流式操作中完成统计+排序需求,实现思路为:先完成分组计数,接着对生成的Map的Entry流做自定义排序,最终收集为保持插入顺序的LinkedHashMap即可,完整代码示例如下:

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

// 示例输入list
List<String> list = List.of("Cat", "Cat", "Cat", "Dog", "Dog", "Rat");

// 1. 按出现次数升序排序
LinkedHashMap<String, Long> sortedAscMap = list.stream()
        // 分组统计出现次数
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        // 转换为Entry流进行排序
        .entrySet()
        .stream()
        // 按统计值升序排列
        .sorted(Map.Entry.comparingByValue())
        // 收集为保持顺序的LinkedHashMap
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldVal, newVal) -> oldVal,
                LinkedHashMap::new
        ));

// 2. 按出现次数降序排序,仅需修改sorted逻辑即可
LinkedHashMap<String, Long> sortedDescMap = list.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet()
        .stream()
        .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldVal, newVal) -> oldVal,
                LinkedHashMap::new
        ));

自定义排序规则说明

  • 如果需要实现复合排序,比如值相同的情况下按key字典序排序,可直接调整sorted方法中的比较器逻辑,示例如下:
.sorted(Map.Entry.<String, Long>comparingByValue()
        .reversed()
        .thenComparing(Map.Entry.comparingByKey())
)
  • 整个逻辑为完整链式调用,不需要额外定义中间变量存储未排序的Map,符合单操作完成的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:36:08