Java Map排序实现代码示例
以下是Java实现Map排序的示例代码:
import java.util.*;
public class MapSortingExample {
public static void main(String[] args) {
// 创建一个Map并添加元素
Map<String, Integer> map = new HashMap<>();
map.put('A', 10);
map.put('B', 5);
map.put('C', 8);
map.put('D', 3);
// 将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> o1, Map.Entry<String, Integer> o2) {
// 按值进行排序(从小到大)
return o1.getValue().compareTo(o2.getValue());
}
});
// 输出排序结果
for (Map.Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + ' : ' + entry.getValue());
}
}
}
输出结果为:
D : 3
B : 5
C : 8
A : 10
在示例代码中,我们首先创建一个Map并添加了一些元素。然后,我们将Map转换为List,并使用Collections.sort方法对List进行排序。在排序过程中,我们使用了一个Comparator对象,它按值进行排序(从小到大)。最后,我们输出了排序结果。
原文地址: https://www.cveoy.top/t/topic/lVfB 著作权归作者所有。请勿转载和采集!