1.使用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);
});
2.使用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);
});
2.1.在TreeMap基础上自定义排序方法文章来源:https://www.toymoban.com/news/detail-705368.html
原文链接:https://blog.csdn.net/zixuexiaobaihu/article/details/109850832文章来源地址https://www.toymoban.com/news/detail-705368.html
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<String, String> treeMap = new TreeMap<>((o1,o2)-> o2.length()-o1.length());
//TreeMap<String, String> 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);
});
到了这里,关于java中对Map中的key顺序排序的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!