HashMap的排序

HashMap<Integer,User>中根据user的age属性进行排序!

思路

使用HashMap的entrySet()方法得到HashMap的所有键值对,转成list集合,然后使用Collections的Sort()方法对list集合进行排序,此时的list集合已经是排好序的,遍历list使用linkedHashMap来接受即可!

代码,(这里我们按照user的age进行升序排列)

 //根据user的age排序
    public static void main(String[] args) {
        Map<Integer,User> map=new HashMap<Integer,User>();
        map.put(1,new User("小明",18));
        map.put(2,new User("小红",12));
        map.put(3,new User("小黑",14));
        map.put(4,new User("小虎",15));
        map.put(5,new User("小龙",17));
        List<Map.Entry<Integer, User>> list=new ArrayList<Map.Entry<Integer, User>>();
        for (Map.Entry<Integer, User> entry :  map.entrySet()) {
            list.add(entry);
        }
        Collections.sort(list, 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();
            }
        });
        Map linkedMap=new LinkedHashMap();
        for (Map.Entry<Integer, User> entry : list) {
            linkedMap.put(entry.getKey(),entry.getValue());
        }
        System.out.println(linkedMap);
    }

控制台结果:

{2=User{username='小红', age=12},
 3=User{username='小黑', age=14},
 4=User{username='小虎', age=15},
 5=User{username='小龙', age=17},
 1=User{username='小明', age=18}}

拿走不谢

猜你喜欢

转载自blog.csdn.net/qq_43338182/article/details/82964813