已知HashMap<Integer,Proson> map,Proson类中有int age,String name属性。请根据Proson中的age进行降序排序。
public class TestMap {
public static void main(String[] args) {
TestMap t = new TestMap();
HashMap
hash = new HashMap<>();
hash.put(1, new User(22, "张三"));
hash.put(2, new User(19, "李四"));
hash.put(3, new User(23, "王五"));
hash.put(4, new User(18, "Tom"));
HashMap
ha = t.Test(hash);
System.out.println("-----------"+ha);
}
private HashMap
Test(HashMap
hash){
Set
> en = hash.entrySet(); List
> list = new ArrayList<>(en); Collections.sort(list, new Comparator
>() { @Override public int compare(Entry
o1, Entry
o2) { return o1.getValue().getAge()-o2.getValue().getAge(); // return o1.getKey()-o2.getKey(); } }); LinkedHashMap
lm = new LinkedHashMap<>(); for (Entry
entry : list) { lm.put(entry.getKey(),entry.getValue()); } return lm; } static class User{ public User(int age, String name) { this.age = age; this.name = name; } int age; String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }