使用List的默认方法 sort 或者 Collections.sort 进行排序这种方法需要对map的key进行转换 Map map=new HashMap();map.put("4","maliu
使用List的默认方法 sort 或者 Collections.sort 进行排序这种方法需要对map的key进行转换
Map<String,String> map=new HashMap<>();map.put("4","maliu");map.put("1","张三");map.put("3","李四");map.put("7","王五");map.put("9","赵六");map.put("2","老六");ArrayList<Map.Entry<String, String>> entries = new ArrayList<>(map.entrySet());//排序条件entries.sort(Comparator.comparingInt(entry -> Integer.parseInt(entry.geTKEy())));//Collections.sort(entries, Comparator.comparingInt(entry -> Integer.parseInt(entry.getKey())));HashMap<String, String> news = new LinkedHashMap<>();for (Map.Entry<String, String> entry : entries) { news.put(entry.getKey(),entry.getValue());}news.forEach((a,b)->{ System.out.printf("k -> %s | v -> %s%n", a,b);});
使用TreeMap的特性进行排序
Map<String,String> map=new HashMap<>();map.put("4","maliu");map.put("1","张三");map.put("3","李四");map.put("7","王五");map.put("9","赵六");map.put("2","老六");TreeMap<String, String> treeMap = new TreeMap<>(map);treeMap.forEach((k,v)->{ System.out.printf("k -> %s | v -> %s%n", k,v);});
1.在TreeMap基础上自定义排序方法
原文链接:https://blog.csdn.net/zixuexiaobaihu/article/details/109850832
Map<String,String> map=new HashMap<>();map.put("1","maliu");map.put("22","张三");map.put("4444","李四");map.put("666666","王五");map.put("55555","赵六");map.put("333","老六");//TreeMap treeMap = new TreeMap<>((o1,o2)-> o2.length()-o1.length()); //TreeMap treeMap2 = new TreeMap<>((o1,o2)-> o1.length()-o2.length()); TreeMap<String, String> treeMap = new TreeMap<>(Comparator.comparingInt(String::length));treeMap.putAll(map);treeMap.forEach((k,v)->{ System.out.printf("k -> %s | v -> %s%n", k,v);});
来源地址:https://blog.csdn.net/weixin_43889494/article/details/131914068
--结束END--
本文标题: java中对Map中的key顺序排序
本文链接: https://lsjlt.com/news/415105.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0