How do I sort the elements of an HashMap according to their values?
本问题已经有最佳答案,请猛点这里访问。
我有以下的
根据值排序最简单的方法是什么?
不能按值对
相反,您可以对条目进行排序:
1 2 3 4 5 6 7 | 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可以按照比较器定义的顺序保存其条目。
最后,我们将得到地图中的第一个键,它应该是最常见的单词(如果多个单词的计数相等,则至少是其中一个)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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 } } |
来源:https://stackoverflow.com/a/1283722/284685
一个解决办法,如果你想让他们按顺序打印(而不是存储)。
创建一个新的映射(
将值列表作为
将
现在迭代
希望这有帮助。