题目
已知一个HashMap<Integer,User>集合, User有name(String)和age(int)属性。请写一个方法实现对HashMap的排序功能,该方法接收HashMap<Integer,User>为形参,返回类型为HashMap<Integer,User>,要求对HashMap中的User的age正序进行排序。排序时key=value键值对不得拆散。
我的代码如下
User类
package com.pojo; public class User { private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } }
业务代码
package com.collection.list; import com.pojo.User; import java.util.*; public class ListDemo { public static void main(String[] args) { HashMap<Integer, User> hashMap = new HashMap<Integer, User>(){ { put(1, new User("小明", 12)); put(2, new User("小张", 16)); put(3, new User("小赵", 11)); put(4, new User("小黄", 10)); put(5, new User("小王", 10)); put(6, new User("小胡", 11)); put(7, new User("小梦", 12)); } }; hashMap = sortMap(hashMap); System.out.println(hashMap); } private static HashMap<Integer, User> sortMap(HashMap<Integer, User> hashMap) { TreeSet<Map.Entry<Integer, User>> entries1 = new TreeSet<Map.Entry<Integer, User>>(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()就会造成数据丢失 if (o1.getValue().getAge() > o2.getValue().getAge()) { return -1; } else { return 1; } } }); entries1.addAll(hashMap.entrySet()); LinkedHashMap linkedHashMap = new LinkedHashMap<Integer, User>(); for (Map.Entry<Integer, User> integerUserEntry : entries1) { linkedHashMap.put(integerUserEntry.getKey(), integerUserEntry.getValue()); } return linkedHashMap; } }
--完--
原文:https://www.cnblogs.com/kitor/p/12681936.html