版权声明:原创文章,不得转载 https://blog.csdn.net/cpongo8/article/details/86703395
package com.baizhi.entity;
import java.util.*;
public class TestUser {
public static void main(String[] args) {
HashMap<Integer, User> map = new LinkedHashMap<>();
map.put(1,new User("zhangsan",25));
map.put(2,new User("lisi",18));
map.put(3,new User("wangwu",23));
System.out.println(map);
HashMap<Integer, User> hashMap = sortHaxhMap(map);
System.out.println(hashMap);
}
public static HashMap<Integer, User> sortHaxhMap(HashMap<Integer, User> map){
//拿到map的键值对集合
Set<Map.Entry<Integer, User>> entrySet = map.entrySet();
//将 set 集合转为 List 集合,为什么,为了使用工具类的排序方法
List<Map.Entry<Integer, User>> list = new ArrayList<>(entrySet);
// 使用 Collections 集合工具类对 list 进行排序,排序规则使用匿名内部类来实现
Collections.sort(list, new Comparator<Map.Entry<Integer, User>>() {
@Override
public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2) {
//按照要求根据user的age进行倒序排序
return o2.getValue().getAge()-o1.getValue().getAge();
}
});
//创建一个新的有序的 HashMap 子类的集合
LinkedHashMap<Integer, User> hashMap = new LinkedHashMap<>();
//将 List 中的数据存储在 LinkedHashMap 中
for (Map.Entry<Integer, User> integerUserEntry : list) {
hashMap.put(integerUserEntry.getKey(),integerUserEntry.getValue());
}
//返回结果
return hashMap;
}
}