手写HashMap排序

/**
 * @author zhongxia creat by 2018/12/17 21:36
 * @info 写注释,认真
 * @motto 努力不会徒劳,爱不会凑巧
 */
public class HashMapTest {
    public static void main(String[] args) {
        HashMap<Integer,User> hashMap = new HashMap<>();
        hashMap.put(1,new User("张三",25));
        hashMap.put(2,new User("李四",22));
        hashMap.put(3,new User("王五",18));
        hashMap.put(4,new User("tom",24));
        hashMap.put(5,new User("jack",20));
        hashMap.put(6,new User("lucy",19));
        hashMap.put(7,new User("bob",17));
        System.out.println(hashMap);
        HashMap<Integer, User> map = hashMapSort(hashMap);
        System.out.println(map);
    }
    public static HashMap<Integer,User> hashMapSort( HashMap<Integer,User> map){
        //首先拿到map的键值对集合
        Set<Map.Entry<Integer, User>> entries = map.entrySet();
        //将set集合转化为List,使用集合类的sort排序方法
        List<Map.Entry<Integer, User>> list = new ArrayList<>(entries);
        //使用Conllections集合工具类对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(); //年龄从大到小排序
                  return o1.getValue().getAge()-o2.getValue().getAge(); //年龄从小到大排序
            }
        });
        LinkedHashMap<Integer, User> hashMap = new LinkedHashMap<>();
        for (Map.Entry<Integer,User> entry:list){
            hashMap.put(entry.getKey(),entry.getValue());
        }
        HashMap<Integer, User> integerUserHashMap = new HashMap<>();
        Collections.synchronizedMap(integerUserHashMap);
        return hashMap;
    }
}

纯手写点个赞!

猜你喜欢

转载自blog.csdn.net/VinceZxy/article/details/89358665