已知一个 HashMap<Integer, User>集合, User 有 name(String)和 age(int)属性。请写一个方法实现对HashMap 的排序功能,该方法接收 HashMap<Integer, User>为形参,返回类型为 HashMap<Integer, User>,要求对 HashMap 中的 User 的 age 倒序进行排序。排序时 key=value 键值对不得拆散。
注意:要做出这道题必须对集合的体系结构非常的熟悉。 HashMap 本身就是不可排序的,但是该道题偏偏让给HashMap 排序,那我们就得想在 API 中有没有这样的 Map 结构是有序的, LinkedHashMap,对的,就是他,他是Map 结构,也是链表结构,有序的,更可喜的是他是 HashMap 的子类,我们返回 LinkedHashMap<Integer,User>HashMap 排序,那我们就得想在 API 中有没有这样的 Map 结构是有序的, LinkedHashMap,对的,就是他,他是Map 结构,也是链表结构,有序的,更可喜的是他是 HashMap 的子类,我们返回 LinkedHashMap<Integer,User>即可,还符合面向接口(父类编程的思想)。
但凡是对集合的操作,我们应该保持一个原则就是能用 JDK 中的 API 就有 JDK 中的 API,比如排序算法我们不应该去用冒泡或者选择,而是首先想到用 Collections 集合工具类。
package HashMapDemo;
public class User {
private String name;
private int age;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
package HashMapDemo;
import java.util.*;
import java.util.Map.Entry;;
public class HashMapTest {
public static void main(String[] args) {
HashMap<Integer,User> hm = new HashMap<>();
User us1 = new User("Mike",22);
User us2 = new User("Joe",18);
User us3 = new User("Doe",27);
User us4 = new User("Rdu",21);
hm.put(1, us1);
hm.put(2, us2);
hm.put(3, us3);
hm.put(4, us4);
//排序后返回一个LinkedHashMap对象,LinkedHashMap存储的键值对是有序的。
HashMap<Integer,User> sorthm = sortHashMap(hm);
Set<Entry<Integer,User>> s = sorthm.entrySet();
for(Entry<Integer,User> entry : s) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
public static HashMap sortHashMap(HashMap hm) {
//Set存储所有键值对
Set<Entry<Integer,User>> set = hm.entrySet();
//转为List因为需要用到Collections自带的sort方法
List<Entry<Integer,User>> list = new ArrayList<>(set);
//重写sort方法,使用匿名内部类
Collections.sort(list, new Comparator<Entry<Integer,User>>(){
@Override
public int compare(Entry<Integer,User> e1,Entry<Integer,User> e2) {
// 根据年龄排序
return e1.getValue().getAge()-e2.getValue().getAge();
}
});
//创建LinkedHashMap对象用来接收List中键值对
LinkedHashMap<Integer,User> lhm = new LinkedHashMap<>();
//遍历存储
for(Entry<Integer, User> entry : list) {
lhm.put(entry.getKey(), entry.getValue());
}
return lhm;
}
}