实现HashMap的排序

已知一个HashMap<Integer, User>集合, User有name (String) 和 age (int) 属性,请写一个方法实现对HashMap的排序功能,该方法接受HashMap<Integer, User>为形参,返回类型为HashMap<Integer, User>,要求对HashMap中的User的age倒序进行排序,排序时key==value键值对不能拆散。

注意:

HashMap本身是不支持排序的,但是该道题偏偏需要排序,那我们想API中是否有Map结构而且是有序的,LinkedHashMap, 其是Map也是基于链表结构,有序的,并且还是HashMap的子类,我们返回LinkedHashMap<Integer, User>即可。

但凡是对集合的操作,我们应该保持一个原则就是能用JDK中的API就用,比如排序算法不选用冒泡或者选择,而是首先想到用Collections集合的工具类。

public class SortTest {
    public static void main(String[] args) {
        HashMap<Integer, User> map = new HashMap<Integer, User>();
        map.put(1, new User("狗娃", 23));
        map.put(2, new User("铁蛋", 18));
        map.put(3, new User("狗蛋", 26));
        System.out.println(map);
        HashMap<Integer, User> sortHashMap = sortHashMap(map);
        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集合   主要是为了使用Collections的排序方法
        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) {
                return o2.getValue().getAge()-o1.getValue().getAge();
            }
        });
        //创建一个新的有序的HashMap子类集合
        LinkedHashMap<Integer, User> linkedHashMap = new LinkedHashMap<>();
        for (Map.Entry<Integer,User> entry : list){
            //将list中的数据存储到新集合中
            linkedHashMap.put(entry.getKey(),entry.getValue());
        }
        //返回集合
        return linkedHashMap;
    }
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章