java中对Map中的key顺序排序
短信预约 -IT技能 免费直播动态提醒
使用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
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341