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;
}
}