题目:已知一个 HashMap<Integer,User>集合, User 有 name(String)和 age(int)属性。请写一个方法实现对
HashMap 的排序功能,该方法接收 HashMap<Integer,User>为形参,返回类型为 HashMap<Integer,User>,
要求对 HashMap 中的 User 的 age 倒序进行排序。排序时 key=value 键值对不得拆散。
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 + '}'; } }