HashMap排序

package cn.timer;

import java.util.*;

public class Main {


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


    public static HashMap<Integer, User> sortHashMap(HashMap<Integer, User> map) {
        ArrayList<Map.Entry<Integer, User>> list = new ArrayList<>(map.entrySet());
        list.sort(new Comparator<Map.Entry<Integer, User>>() {
            @Override
            public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2) {
                return o1.getValue().getAge()-o2.getValue().getAge();
            }
        });

        LinkedHashMap<Integer, User> linkedHashMap = new LinkedHashMap<>();
        for(Map.Entry<Integer,User>entry : list){
            linkedHashMap.put(entry.getKey(),entry.getValue());
        }

        return linkedHashMap;
    }
}




 

發佈了23 篇原創文章 · 獲贊 17 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章