最近看到一道非常有趣的题,作者对集合的体系结构很了解,HashMap 本身就是不可排序的,但是该道题偏偏让给HashMap 排序,在 API 中LinkedHashMap是Map 结构,也是链表结构,有序的,是 HashMap 的子类,返回 LinkedHashMap<Integer,User>即可,还符合面向接口(父类编程的思想)。
已知一个 HashMap<Integer,User>集合, User 有 name(String)和 age(int)属性。请写一个方法实现对HashMap 的排序功能,该方法接收 HashMap<Integer,User>为形参,返回类型为 HashMap<Integer,User>,要求对 HashMap 中的 User 的 age 倒序进行排序。排序时 key=value 键值对不得拆散。
public class HashMapTest {
public static void main(String[] args) {
HashMap<Integer, User> users = new HashMap<>();
users.put(1, new User("张三", 25));
users.put(3, new User("李四", 22));
users.put(2, new User("王五", 28));
System.out.println(users);
HashMap<Integer,User> sortHashMap = sortHashMap(users);
System.out.println(sortHashMap);
}
public static HashMap<Integer, User> sortHashMap(HashMap<Integer, User> map) {
Set<Entry<Integer, User>> entrySet = map.entrySet();
List<Entry<Integer, User>> list = new ArrayList<Entry<Integer, User>>(entrySet);
Collections.sort(list, new Comparator<Entry<Integer, User>>() {
@Override
public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) {
return o2.getValue().getAge()-o1.getValue().getAge();
}
}};
LinkedHashMap<Integer, User> linkedHashMap = new LinkedHashMap<Integer, User>();
for(Entry<Integer, User> entry : list){
linkedHashMap.put(entry.getKey(), entry.getValue());
}
return linkedHashMap;
}
}