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);
}
欢迎一起来学习和指导,谢谢关注!
本文来自博客园,作者:xiexie0812,转载请注明原文链接:https://www.cnblogs.com/mask-xiexie/p/16199048.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了