前言:
首先我们要知道HashMap 本身就是不可排序的,但这里我们要使HashMap 排序,那我们就得想在 API 中有没有这样的 Map 结构是有序的,那就需要用上LinkedHashMap,它是 Map 结构,也是链表结构有序的,更重要的是它是 HashMap 的子类。
但凡是对集合的操作,我们应该保持一个原则就是能用 JDK 中的 API 就有 JDK 中的 API,比如排序算法我们不应该去用冒泡或者选择,而是首先想到用 Collections 集合工具类。
场景:
已知一个 HashMap集合, User有 name(String)和 age(Integer)属性。请写一个方法实现对 HashMap 的排序功能,该方法接收 HashMap为形参,返回类型为 HashMap, 要求对 HashMap 中的 User的 age 升序排序。排序时 key=value 键值对不得拆散。
代码实现:
这里使用了lombok插件,减免了get、set的书写
@Data
public class User {
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
}
public class TestMain1 {
public static void main(String[] args) {
HashMap<Integer, User> userHashMap = new HashMap<>();
userHashMap.put(1, new User("小明", 15));
userHashMap.put(2, new User("小黑", 19));
userHashMap.put(3, new User("小白", 16));
System.out.println("------------排序前-----------");
System.out.println(userHashMap);
HashMap<Integer, User> sortHashMap = sortHashMap(userHashMap);
System.out.println("------------排序后-----------");
System.out.println(sortHashMap);
}
public static HashMap<Integer, User> sortHashMap(HashMap<Integer, User> map) {
// 首先拿到 map 的键值对集合
Set<Map.Entry<Integer, User>> entrySet = map.entrySet();
// 将 set 集合转为 List 集合,为什么,为了使用工具类的排序方法
List<Map.Entry<Integer, User>> list = new ArrayList<Map.Entry<Integer, User>>(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 的升序进行排,如果是倒序就是o2-o1
return o1.getValue().getAge() - o2.getValue().getAge();
}
});
//创建一个新的有序的 HashMap 子类的集合
LinkedHashMap<Integer, User> linkedHashMap = new LinkedHashMap<Integer, User>();
//将 List 中的数据存储在 LinkedHashMap 中
for (Map.Entry<Integer, User> entry : list) {
linkedHashMap.put(entry.getKey(), entry.getValue());
}
//返回结果
return linkedHashMap;
}
}
输出:
其中我们会发现这一步其实就是对list的排序