美文网首页
HashMap排序题

HashMap排序题

作者: 今天也要努力呀y | 来源:发表于2019-10-29 12:55 被阅读0次

对一个HashMap<Integer,User>,User有name和age属性,要求对HashMap排序,通过User中的age的倒序进行排序.
分析:我们都知道HashMap是无序的,而这道题要排序,而且还要按照User的age进行排序,我们新建了一个方法sortHashMap,在里面我们使用LinkedHashMap这个有序的子类,当我们使用Collections进行排序时,又发现第一个参数必须传输一个list,所以我们想办法怎么样把一个Map改成一个List,方法就是,Map先改为一个set,然后把Set改为一个list,最后把数据传到LinkedHashMap中,传回
先定义一个User类

public class User {
    private String name;
    private int age;

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User="+name+"Age="+age;
    }
}

import java.util.Scanner;
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        HashMap<Integer,User> hashMap = new HashMap<Integer, User>();
        User user = new User();
        user.setName("张三");
        user.setAge(23);
        hashMap.put(1,user);
        User user1 = new User();
        user1.setName("李四");
        user1.setAge(24);
        hashMap.put(2,user1);
        User user2 = new User();
        user2.setName("王五");
        user2.setAge(21);
        hashMap.put(3,user2);
        System.out.println("排序前"+hashMap);
        HashMap<Integer,User> sortedHashmap  = sortHashMap(hashMap);
        System.out.println("排序前"+sortedHashmap);
    }

    private static LinkedHashMap<Integer,User> sortHashMap(HashMap<Integer,User> hashMap) {
        //HashMap无序,所以使用HashMap的一个子类,有序的LinkedHashMap
        LinkedHashMap newhashmap = new LinkedHashMap<Integer,User>();
        //凡是要对集合排序,就使用工具类去排序
        //因为只对list有用,所以先转换为set(map无法直接转换为list)
        Set<Map.Entry<Integer,User>> entrySet = hashMap.entrySet();
        ArrayList<Map.Entry<Integer,User>> list = new ArrayList<>(entrySet);
        //对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();
            }
        });
        //将排好序的list转换为LinkedHashMap
        for (int i=0;i<list.size();i++){
            Map.Entry<Integer,User> entry = list.get(i);
            newhashmap.put(entry.getKey(),entry.getValue());
        }

        return newhashmap;
    }
}


相关文章

网友评论

      本文标题:HashMap排序题

      本文链接:https://www.haomeiwen.com/subject/giiwvctx.html