基于Value然后Key对HashMap进行排序?

可能重复:
如何在Java中的值上对Map 进行排序?

我有一个类型的HashMap:

HashMap h = new HashMap(); 

HashMap包含一个字符串列表,而Integer是一个计数器,用于查找String的次数。 我希望能够做的是基于整数对HashMap进行排序,然后按字符串的字母顺序排序。

目前,我正在记录一个单词的最大出现(变量名为max)并显示如下值:

 public void print(){ while(max > 0){ for (String key : h.keySet()){ if(h.get(key) == max){ System.out.println(key + " " + h.get(key)); } } max--; } } 

它不按字母顺序对值进行排序,也访问HashMap最大* h(大小)次。

什么是更好的解决方案?

这是一个Comparator ,它使用Comparable键和值对Map.Entry对象进行排序:

 public class ValueThenKeyComparator, V extends Comparable> implements Comparator> { public int compare(Map.Entry a, Map.Entry b) { int cmp1 = a.getValue().compareTo(b.getValue()); if (cmp1 != 0) { return cmp1; } else { return a.getKey().compareTo(b.getKey()); } } } 

您将所有映射条目放入列表中,然后对其进行排序:

 List> list = new ArrayList>(h.entrySet()); Collections.sort(list, new ValueThenKeyComparator()); 

看看Google Guava库 。 它有一个Multiset为你做计算,然后你有Ordering类,简化了排序。

您需要做的就是用字符串填充Multiset 。 它会为你保持频率。 然后,您可以使用Ordering对这些字符串进行Ordering

可能不是最优雅的解决方案,但这怎么样?

 //TreeSet with reversed natural ordering (big integers first) Map> h = new TreeMap>(Collections.reverseOrder()); //and use TreeSet for the set... // ... // for(Map.Entry> entry : h.entrySet()){ for(String str : entry.getValue()){ System.out.println(str + " has occured " + entry.getKey() + " times."); } } 

您可以使用SortedMap界面对HashMap进行排序。 这很简单 – 自动排序。 请参阅http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html 。 我这里没有包含任何代码,但如果您需要,只需添加注释即可。 我会给你一个示例代码。