jdk7 如何给map排序 java
时间: 2023-05-04 15:02:31 浏览: 74
在JDK7及以上版本中,可以通过实现Comparator接口来对Map进行排序。Comparator接口是一个用于比较对象的接口,它有一个compare()方法,用于比较两个对象的大小。我们可以通过实现这个接口来定义Map的排序规则。
首先,我们需要将Map的entrySet()方法返回的Set集合转换成List集合,然后使用Collections.sort()方法对List集合进行排序。在排序时,我们需要自定义一个Comparator对象来指定排序规则。对于Map而言,我们可以按照key或value进行排序。
下面是一个按照value排序的示例代码:
Map<String, Integer> map = new HashMap<String, Integer>();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
for (Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
在这个示例中,我们首先将Map的entrySet()方法返回的Set集合转换成List集合,然后通过Collections.sort()方法对List集合进行排序。在排序时,我们自定义了一个匿名内部类实现Comparator接口,它将两个Entry对象的value进行比较,并返回比较结果。最后,我们遍历排序后的List集合,并输出每个entry的key和value。
当然,如果要按照key进行排序,我们只需要在Comparator的compare()方法中将o1.getKey()和o2.getKey()进行比较即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)