我有以下内容HashMap
:
HashMap<String, Integer> counts = new HashMap<String, Integer>();
根据值订购它的最简单方法是什么?
我有以下内容HashMap
:
HashMap<String, Integer> counts = new HashMap<String, Integer>();
根据值订购它的最简单方法是什么?
您不能Map
按值对 a 进行排序,尤其是 a 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());
}
});
将按计数升序对条目进行排序。
您可以使用 . 从地图中获取一组条目 ( Set
of ) 。只需遍历它们,并通过 . 检查值。Map.Entry
map.entrySet()
getValue()
一个解决方法,如果你想让他们按顺序打印它们(不存储)。
创建一个新的 Map ( tempMap
) 并将您的值作为键和键作为值。要使键唯一,请在每个键中添加一些唯一值,例如 key1 = value1+@0。
获取值map.values()
列表作为列表myVlues
myVlues
将列表排序为Collections.sort(myVlues)
现在迭代myVlues
,获取对应key
的 from tempMap
,恢复键,例如 key.substring(0, key.length-2) 并打印键和值对。
希望这可以帮助。
TreeMap可以按照Comparator定义的顺序保留其条目。
counts
地图中的所有条目放入比较器中。最后,我们将获得地图中的第一个键,它应该是最常见的词(或者至少其中一个,如果多个词具有相同的计数)。
public class Testing {
public static void main(String[] args) {
HashMap<String,Double> counts = new HashMap<String,Integer>();
// Sample word counts
counts.put("the", 100);
counts.put("pineapple",5);
counts.put("a", 50);
// Step 1: Create a Comparator that order by value with greatest value first
MostCommonValueFirst mostCommonValueFirst = new MostCommonValueFirst(counts);
// Step 2: Build a TreeMap that uses that Comparator
TreeMap<String,Double> sortedMap = new TreeMap<String,Integer (mostCommonValueFirst);
// Step 3: Populate TreeMap with values from the counts map
sortedMap.putAll(counts);
// Step 4: The first key in the map is the most commonly used word
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;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return 1;
} else {
return -1;
} // returning 0 would merge keys
}
}