我有以下的
什么是根据值排序的最简单方法?
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());
}
});
将会按照计数的升序对条目进行排序。
TreeMap可以按照Comparator定义的顺序保留其条目。
counts
映射中。最后,我们将获取地图中的第一个键,这应该是最常见的单词(如果有多个单词计数相等,则至少是其中之一)。
public class Testing {
public static void main(String[] args) {
HashMap<String,Double> counts = new HashMap<String,Integer>();
// 样本单词计数
counts.put("the", 100);
counts.put("pineapple",5);
counts.put("a", 50);
// 步骤1:创建一个比较器,按最大值排序
MostCommonValueFirst mostCommonValueFirst = new MostCommonValueFirst(counts);
// 步骤2:构建一个使用该比较器的TreeMap
TreeMap<String,Double> sortedMap = new TreeMap<String,Integer (mostCommonValueFirst);
// 步骤3:用计数映射中的值填充TreeMap
sortedMap.putAll(counts);
// 步骤4:地图中的第一个键是最常用的单词
System.out.println("Most common word: " + sortedMap.firstKey());
}
}
private class MostCommonValueFirst implements Comparator<String> {
Map<String, Integer> base;
public MostCommonValueFirst(Map<String, Integer> base) {
this.base = base;
}
// 注意:此比较器施加的排序与相等不一致。
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return 1;
} else {
return -1;
} // 返回0将合并键
}
}
TreeMap
而言,它本质上是一个可变的键。 - Steve Kuo如果您想按顺序打印它们(而不是存储),则可以使用以下解决方法:
创建一个新的Map(tempMap
),将您的值作为键,将键作为值。为了使键唯一,请在每个键中添加一些唯一值,例如key1 = value1+@0。
将值列表作为map.values()
获取到列表myVlues
中。
对myVlues
列表进行排序,使用Collections.sort(myVlues)
。
现在迭代myVlues
,从tempMap
获取相应的key
,恢复键,例如key.substring(0,key.length-2),然后打印键和值对。
希望这可以帮助您。
HashMap
,为什么不创建一个包含单词作为String
、计数作为int
的类,并实现 Comparable 接口以查找最大值,然后将所有这些对象插入到最大堆中,并找到堆的根节点呢? - Zéychin