常用Map比较:
HashMap | TreeMap | Hashtable | LinkedHashMap | |
排序 | 根据key的hashCode进行排序 | 根据key默认升序排序(可以通过排序比较器Comparater定制) | 类似HashMap | 按照插入顺序进行排序 |
null值 | 1个key==null(多了会覆盖) | key != null | key != null | key == null |
n个value==null | value==null | value != null | value == null | |
是否同步 | 非同步 | 非同步 | 同步(同时只能写入一个-->写入速度慢) | 非同步 |
遍历速度 | 快 | 比HashMap慢 |
HashMap排序
Map<String,String> map = new HashMap( );
map.put("d", "ddddd");
map.put("b", "bbbbb");
map.put("a", "aaaaa");
map.put("c", "ccccc");
List<Map.Entry<String,String>> list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
//升序排序
return o1.getValue().compareTo(o2.getValue());
}
});
for (Map.Entry<String, String> entry : list) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
输出结果:
a:aaaaa
b:bbbbb
c:ccccc
d:ddddd
Map<String, Integer> map1 = new HashMap<>();
map1.put("Back-fire",12);
map1.put("Isotopes of palladium",10);
map1.put("Derangement",9);
map1.put("Focal subgroup theorem",5);
map1.put("Group selection",8);
List<Map.Entry<String, Integer>> list = map1.entrySet().stream()
.sorted((entry1, entry2) -> entry1.getValue().compareTo(entry2.getValue()))
.collect(Collectors.toList());
System.out.println(list);