HashMap排序练习
已知一个 HashMap<Integer,User>集合, User 有 name(String)和 age(int)属性。写一个方法实现对HashMap 的排序功能,该方法接收 HashMap<Integer,User>为形参,返回类型为 HashMap<Integer,User>,要求对 HashMap 中的 User 的 age 顺序进行排序。排序时 key=value 键值对不得拆散。
import java.util.*;
public class SortMap {
public static void main(String[] args) {
HashMap<Integer, User> map = new HashMap<>();
map.put(1,new User("张无忌",30));
map.put(2,new User("周芷若",25));
map.put(3,new User("赵敏",28));
//调用方法进行排序
HashMap linkedHashMap = sortMap(map);
System.out.println(linkedHashMap);
}
/**
* 给MAP进行排序
* @param map
* @return LinkedHashMap
*/
public static HashMap sortMap(Map<Integer,User> map){
//准备LinkedHashMap用来存放排序后的数据
LinkedHashMap<Integer, User> linkedHashMap = new LinkedHashMap<>();
//遍历map得到单列集合
Set<Map.Entry<Integer, User>> entries = map.entrySet();
//使用collections集合工具类进行排序
List<Map.Entry<Integer, User>> list = new ArrayList<>(entries);
Collections.sort(list, new Comparator<Map.Entry<Integer, User>>() {
@Override
public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2) {
//比较年龄
int num = o1.getValue().getAge() - o2.getValue().getAge();
//如果年龄一样,再进行比较序号
return num == 0 ? o1.getKey()-o2.getKey() : num;
}
});
//遍历存入LinkedHashMap
list.forEach(entrie->{
linkedHashMap.put(entrie.getKey(),entrie.getValue());
});
return linkedHashMap;
}
}
LinkedHashMap是Map 结构,也是链表结构,有序的,还是 HashMap 的子类,我们可以返回 LinkedHashMap<Integer,User>,还符合面向接口(父类编程的思想)。
但凡是对集合的操作,我们应该保持一个原则就是能用 JDK 中的 API 就有 JDK 中的 API,比如排序算法我们不应该去用冒泡或者选择,而是首先想到用 Collections 集合工具类。
以上就实现了HashMap的排序。