根据Java中的值对地图进行排序的最简单方法是什么?

我希望我的哈希值根据值按降序排序。 我如何用Java做到这一点?

HashMap (及其遗留的前身Hashtable )本质上是无序的。 即使你对它进行排序,它仍将是无序的。 如果要维护插入顺序,请改用LinkedHashMap 。 如果要对进行自动排序,无论插入顺序如何,请改用SortedMap

如果要对进行排序,那么基本上需要将键/值对放在另一种可排序的数据结构中,例如List> ,然后使用Collections#sort()对其进行Collections#sort()Compatator>帮助下,最后用它重新填充LinkedHashMap (不是HashMap否则你将再次失去排序)。

这是一个基本的例子(抛开明显的运行时exception处理):

 // Prepare. Map map = new HashMap(); map.put("foo", "bar"); map.put("bar", "waa"); map.put("waa", "foo"); System.out.println(map); // My JVM shows {waa=foo, foo=bar, bar=waa} // Get entries and sort them. List> entries = new ArrayList>(map.entrySet()); Collections.sort(entries, new Comparator>() { public int compare(Entry e1, Entry e2) { return e1.getValue().compareTo(e2.getValue()); } }); // Put entries back in an ordered map. Map orderedMap = new LinkedHashMap(); for (Entry entry : entries) { orderedMap.put(entry.getKey(), entry.getValue()); } System.out.println(orderedMap); // {foo=bar, waa=foo, bar=waa} 

要对其进行排序,请使用以下Comparator 。 基本上只需交换条目进行比较:

 Collections.sort(entries, new Comparator>() { public int compare(Entry e1, Entry e2) { return e2.getValue().compareTo(e1.getValue()); // Sorts descending. } }); 

使用Collections.reverseOrder() 。

我是这样做的:

 public static > Map sortByValues(final Map map) { Comparator valueComparator = new Comparator() { public int compare(K k1, K k2) { int compare = map.get(k2).compareTo(map.get(k1)); if (compare == 0) return 1; else return compare; } }; Map sortedByValues = new TreeMap(valueComparator); sortedByValues.putAll(map); return sortedByValues; 

}