java-HashMap、TreeMap、LinkedHashMap、ArrayList、LinkedList使用笔记
背景
Map<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("One", 1);
unsortedMap.put("Two", 2);
unsortedMap.put("Three", 3);
unsortedMap.put("Four", 4);
一、关于排序
- TreeMap:默认按照key排序
- 按照value排序,可使用如下代码
public static Map<String, Integer> sortEnemyMap(Map<String, Integer> unsortedMap){
List<Map.Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());
// Sort the list based on values
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
//由大到小
return (o2.getValue()).compareTo(o1.getValue());
//由小到大
//return (o1.getValue()).compareTo(o2.getValue());
}
});
// Convert list to map again
Map<String, Integer> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
二、关于转换
- HashMap转TreeMap
Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
- HashMap转LinkedList
List<Map.Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());