java 给map排序
时间: 2023-08-02 07:07:30 浏览: 74
在Java中,可以使用TreeMap来对Map进行排序。TreeMap是通过红黑树实现的,可以根据键的自然顺序或自定义的Comparator对键进行排序。以下是一个示例代码:
```java
import java.util.*;
public class MapSortExample {
public static void main(String[] args) {
// 创建一个Map
Map<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 15);
map.put("grape", 5);
// 将Map转化为List
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
// 使用Collections.sort对List进行排序
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
// 创建排序后的Map
Map<String, Integer> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
System.out.println(sortedMap);
}
}
```
在上面的代码中,我们将Map转换为List,然后使用Collections.sort对List进行排序。我们使用Comparator来指定排序顺序,这里是按照值的大小进行升序排序。最后,我们将排序后的Map存储在一个LinkedHashMap中,以保持插入顺序。