map排序

前提:map必须指定类型,比如
正例:Map<String,String> ids = new HashMap<>();

1. 按倒序排序

2. 按key正序排序

3. 或者常见一个新的map

代码如下:

@Test
public void test4() {

    Map<String, Object> result = new HashMap<String, Object>();
    result.put("id", 1);
    result.put("type", "type");
    result.put("key","key");
    result.put("value","value");
    result.put("status",0);
    result.put("createDate", new Date());
    result.put("updateDate",new Date());
    result.put("sort","亚瑟");

    Map<String, Object> finalMap = new LinkedHashMap<>();
    // 1. 按倒序排序
    //result.entrySet().stream()
    //        .sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
    //        .forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));

    // 2. 按key正序排序:
    //result.entrySet().stream()
    //        .sorted(Comparator.comparing(e -> e.getKey()))
    //        .forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));
    //
    //System.out.println(finalMap);
    
    // 或者常见一个新的map
    Map<String, Object> finalMapNew = result.entrySet().stream()
            .sorted(Comparator.comparing(e -> e.getKey()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> oldVal, LinkedHashMap::new));

    System.out.println(finalMapNew);
}
posted @   xiexie0812  阅读(124)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示