<分区>
我有以下 HashMap
:
HashMap<String, Integer> counts = new HashMap<String, Integer>();
根据值对其进行排序的最简单方法是什么?
<分区>
我有以下 HashMap
:
HashMap<String, Integer> counts = new HashMap<String, Integer>();
根据值对其进行排序的最简单方法是什么?
最佳答案
您不能根据值对 Map
进行排序,尤其是 HashMap
,它根本无法排序。
相反,您可以对条目进行排序:
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(
Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
return entry1.getValue().compareTo(entry2.getValue());
}
});
将按计数的升序对条目进行排序。
关于java - 如何根据值对 HashMap 的元素进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12919659/