Sorting a HashMap based on Value, then Key?

Possible duplicate:
How to sort a <Key, Value> map by values ​​in Java?

I have a HashMap type:

HashMap<String, Integer> h = new HashMap<String, Integer>(); 

HashMap contains a list of strings, and Integer is a counter for the number of times the String was found. What I would like to do is sort the HashMap based on integers and then alphabetically the lines.

At the moment, I save the record of the largest occurrence of the word (a variable named max) and displaying the values ​​as follows:

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

Which does not sort the values ​​in alphabetical order, it also refers to the hashMap max * h (size) moment.

What is the best solution?

+5
source share
4 answers

Here's a Comparator that sorts Map.Entry objects using Comparable keys and values:

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

You put all the map entries in a list, and then sorted this:

 List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(h.entrySet()); Collections.sort(list, new ValueThenKeyComparator<String, Integer>()); 
+8
source

Check out the Google Guava libraries . It has a Multiset , which performs the calculation for you, and then you Ordering , which simplifies the sorting.

All you have to do is populate the Multiset your lines. It will maintain the frequency for you. Then you can sort by these lines with Ordering .

+3
source

This may not be the most elegant solution, but how about this?

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

you can use the SortedMap interface to sort the HashMap. It is very simple - automatic sorting. See http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html . I have not added the code here, but if you need to, just add a comment. I will give you sample code.

-2
source

All Articles