HashMap排序题

出处:从黑马程序员的面试宝典beta5.0pdf里看到的。

题目:

已知一个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>即可,还符合面向接口(父类编程的思想)。但凡是对集合的操作,我们应该保持一个原则就是能用JDK中的API就有JDK中的API,比如排序算法我们不应该去用冒泡或者选择,而是首先想到用Collections集合工具类。

我的答案:

package lhh.collection;

import java.util.*;

/**
 * @program: IdeaJava
 * @Date: 2020/1/3 13:50
 * @Author: lhh
 * @Description:
 */

class User{
    public String name;
    public int age;
    public User(){}
    public User(String name ,int age)
    {
        this.name = name;
        this.age = age;
    }
    public String toString()
    {
        return "user [name="+ name+ ",age="+age+"]";
    }
}
public class HashMapTestSortApp {

    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<>(entrySet);
        //使用collection集合工具对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().age-o1.getValue().age;
            }
        });

        //创建一个新的有序的HashMap子类的集合
        LinkedHashMap<Integer,User> linkedHashMap = new LinkedHashMap<>();

        //将List中的数据存储在linkedHashMap中
        for(Map.Entry<Integer,User> entry:list)
        {
            linkedHashMap.put(entry.getKey(),entry.getValue());
        }
        return linkedHashMap;


    }

    public static void main(String[] args) {

        HashMap<Integer, User> users = new HashMap<>();
        users.put(1,new User("张三",25));
        users.put(2,new User("李四",23));
        users.put(3,new User("王五",27));
        System.out.println(users);

        HashMap<Integer,User> sortHashMap = sortHashMap(users);
        System.out.println(sortHashMap);

    }
}

猜你喜欢

转载自www.cnblogs.com/lhh666/p/12145622.html