》
hashMap是无法排序的,那怎么对其排序?
1、思路
- 只有转化为list 集合,对list进行排序
- 对排完序的list 集合遍历装进有序的LinkedMap 中,完成排序;
- hashMap的排序、依据年龄倒序
package com.baidu;
import com.baidu.pojo.User;
import java.util.*;
/**
* @auther SyntacticSugar
* @data 2018/12/7 0007上午 10:04
*/
public class HashMapTest {
public static void main(String[] args) {
HashMap<Integer, User> hashMap = new HashMap<Integer, User>();
hashMap.put(1,new User("张三1",25));
hashMap.put(2,new User("张三2",26));
hashMap.put(3,new User("张三3",16));
hashMap.put(4,new User("张三4",20));
//获取entries、将其转化为list
Set<Map.Entry<Integer, User>> entries = hashMap.entrySet();
ArrayList<Map.Entry<Integer, User>> list = new ArrayList<Map.Entry<Integer, User>>(entries);
// 使用工具类Collections 对list 遍历排序
Collections.sort(list, new Comparator<Map.Entry<Integer, User>>() {
public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2) {
int i = o2.getValue().getAge() - o1.getValue().getAge();
return i;
}
});
//创建linkedHashMap填充元素、 遍历查看效果
LinkedHashMap<Integer, User> map = new LinkedHashMap<Integer, User>();
for (Map.Entry<Integer, User> userEntry : list) {
map.put(userEntry.getKey(), userEntry.getValue());
}
//
System.out.println(map);
}
}
19.01.08更新
hashmap 对空值null的处理
putForNullKey 的方法、
if (key == null)
return putForNullKey(value);
//那就看看这个putForNullKey是怎么处理的吧。
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}