Map排序(按key排序,按value排序)
时间: 2023-08-04 07:28:40 浏览: 84
对于按key排序,可以使用TreeMap来实现。TreeMap是按照key的自然顺序或者指定的比较器排序的。
示例代码如下:
```java
import java.util.*;
public class MapSortByKey {
public static void main(String[] args) {
Map<String, Integer> map = new TreeMap<>();
map.put("apple", 4);
map.put("banana", 2);
map.put("orange", 3);
map.put("peach", 1);
// 按key升序排列
Map<String, Integer> sortedByKeyMap = new TreeMap<>(map);
System.out.println(sortedByKeyMap); // {apple=4, banana=2, orange=3, peach=1}
// 按key降序排列
Map<String, Integer> sortedByKeyDescMap = new TreeMap<>(Collections.reverseOrder());
sortedByKeyDescMap.putAll(map);
System.out.println(sortedByKeyDescMap); // {peach=1, orange=3, banana=2, apple=4}
}
}
```
对于按value排序,可以将Map转化为List,然后通过Comparator来实现排序。
示例代码如下:
```java
import java.util.*;
public class MapSortByValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 4);
map.put("banana", 2);
map.put("orange", 3);
map.put("peach", 1);
// 按value升序排列
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, Comparator.comparing(Map.Entry::getValue));
Map<String, Integer> sortedByValueMap = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : list) {
sortedByValueMap.put(entry.getKey(), entry.getValue());
}
System.out.println(sortedByValueMap); // {peach=1, banana=2, orange=3, apple=4}
// 按value降序排列
List<Map.Entry<String, Integer>> descList = new ArrayList<>(map.entrySet());
descList.sort(Collections.reverseOrder(Comparator.comparing(Map.Entry::getValue)));
Map<String, Integer> sortedByValueDescMap = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : descList) {
sortedByValueDescMap.put(entry.getKey(), entry.getValue());
}
System.out.println(sortedByValueDescMap); // {apple=4, orange=3, banana=2, peach=1}
}
}
```
阅读全文