java元帅

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  49 随笔 :: 0 文章 :: 0 评论 :: 19841 阅读

map中的key进行排序

   Map<String, String> value = entry.getValue();         

Map<String, String> collect = value.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> oldVal, LinkedHashMap::new));

 

若数据是 List<Map<String, Object>> value,对其进行排序:

复制代码
 private List<Map<String, Object>> dealSorted(List<Map<String, Object>> value) {
        Collections.sort(value, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String cserialno1 = o1.get("serialNo").toString();
                String cserialno2 = o2.get("serialNo").toString();
                return cserialno2.compareTo(cserialno1);
            }
        });
        return value;
    }
复制代码

 

2、使用Java流来做排序:

复制代码
public static void main(String[] args) {
        Map<String, Integer> codes = new HashMap<>();
        codes.put("United States", 1);
        codes.put("Germany", 49);
        codes.put("France", 33);
        codes.put("China", 86);
        codes.put("Pakistan", 92);
        Map<String, Integer> sortedMap = codes.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(
                        Collectors.toMap(
                                Map.Entry::getKey,
                                Map.Entry::getValue,
                                (oldVal, newVal) -> oldVal,
                                LinkedHashMap::new
                        )
                );

        sortedMap.entrySet().forEach(System.out::println);
    }
复制代码

 

posted on   java元帅  阅读(7009)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签
点击右上角即可分享
微信分享提示