java中对Map中的key顺序排序

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://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<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);
});

猜你喜欢

转载自blog.csdn.net/weixin_43889494/article/details/131914068