[Map]利用LinkedHashMap來排序

題目:已知一個 HashMap<Integer,User>集合, User 有 name(String)和 age(int)屬性。請寫一個方法實現對
HashMap 的排序功能,該方法接收 HashMap<Integer,User>爲形參,返回類型爲 HashMap<Integer,User>,
要求對 HashMap 中的 User 的 age 倒序進行排序。排序時 key=value 鍵值對不得拆散。ide

public class HashMapTest {
    public static void main(String[] args) {
        HashMap<Integer, User> users = new HashMap<Integer, User>();
        users.put(1, new User("張三", 25L));
        users.put(3, new User("李四", 22L));
        users.put(2, new User("王五", 28L));
        System.out.println(users);
        HashMap<Integer, User> sortHashMap = sortHashMap(users);
        System.out.println(sortHashMap);
    }

    public static HashMap<Integer, User> sortHashMap(HashMap<Integer, User> map) {
        HashMap<Integer, User> linkedHashMap = new LinkedHashMap<Integer, User>();
        Set<Map.Entry<Integer, User>> entrySet = map.entrySet();
        List<Map.Entry<Integer, User>> list = new ArrayList<Map.Entry<Integer, User>>();
        list.addAll(entrySet);
        //根據年齡排倒序
        Collections.sort(list, new Comparator<Map.Entry<Integer, User>>() {
            public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2) {
                if (o1.getValue().getAge() - o2.getValue().getAge() > 0) {
                    return -1;
                } else if (o1.getValue().getAge() - o2.getValue().getAge() < 0) {
                    return 1;
                }
                return 0;
            }
        });
        for (Map.Entry<Integer, User> entry : list) {
            linkedHashMap.put(entry.getKey(), entry.getValue());
        }
        return linkedHashMap;
    }
}
public class User {
    private String username;
    private Long age;

    public Long getAge() {
        return age;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public User(String username, Long age) {
        this.username = username;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}
相關文章
相關標籤/搜索