2018/09/12 18:21

HashMap 的排序功能，该方法接收 HashMap<Integer，User>为形参，返回类型为 HashMap<Integer，User>，

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) {
Set<Map.Entry<Integer, User>> entrySet = map.entrySet();
List<Map.Entry<Integer, User>> list = new ArrayList<Map.Entry<Integer, User>>();
//根据年龄排倒序
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) {
}
}
}
public class User {
private Long age;

public Long getAge() {
return age;
}

public void setAge(Long age) {
this.age = age;
}

}

}

public User(String username, Long age) {
this.age = age;
}

@Override
public String toString() {
return "User{" +
", age=" + age +
'}';
}
}

1
0 收藏

0 评论
0 收藏
1