背景
java
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排序,可使用如下代码
java
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 (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());
}
System.out.println("Sorted map by value: " + sortedMap);
二、关于转换
- HashMap转TreeMap
java
Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
- HashMap转LinkedList
java
List<Map.Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());