title: Sorting a HashMap based on Value then Key?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java">How to sort a Map&lt;Key, Value&gt; on the values in Java?</a>  </p>
  </blockquote>
  
  
  
  <p>I have a HashMap of the type:</p>
  
  <pre><code>HashMap&lt;String, Integer&gt; h = new HashMap&lt;String, Integer&gt;();
  </code></pre>
  
  <p>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.</p>
  
  <p>At the moment I am keeping a record of the largest occurrence of a word (variable named max) and displaying the values as follows:</p>
  
  <pre><code>public void print(){
      while(max &gt; 0){
         for (String key : h.keySet()){
             if(h.get(key) == max){
                 System.out.println(key + " " + h.get(key));
             }
         }
         max--;
      }
  }
  </code></pre>
  
  <p>Which doesn't sort the values alphabetically, also it accesses the HashMap max*h(size) times.</p>
  
  <p>What is the better solution?</p>