Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
I have a HashMap of the type:
HashMap<String, Integer> h = new HashMap<String, Integer>();
The HashMap contains a list of Strings and the Integer is a counter for the number of times that String has been found. What I would like to be able to do is sort the HashMap based on the Integers, then on the alphabetical order of the Strings.
At the moment I am keeping a record of the largest occurrence of a word (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 doesn't sort the values alphabetically, also it accesses the HashMap max*h(size) times.
What is the better solution?enter code here