title: Sorting HashMap by value using a TreeMap and Comparator
body: <p>Im using the following code to create a hashmap and then sort the values in the hashmap by using a treemap and a comparator. However, the output is rather unexpected. 
  So any thoughts as to what Im doing wrong would be helpful</p>
  
  <p>Code</p>
  
  <pre><code>public static void main(String[] args) {
      System.out.println("Most freq"+mostFreq(" i me hello hello hello me"));
  }
  
  
  public static String[] mostFreq(String str){
  
      if ((str==null)||( str.trim().equalsIgnoreCase("")))
          return null;
  
      String[] arr = new String[10];
  
      String[] words= str.split(" ");
  
      Map &lt;String,Integer&gt; map = new HashMap&lt;String,Integer&gt;();
  
      for (String word :words)
      { 
          int count =0;
          if (map.containsKey(word))
          {     
              count= map.get(word);
              map.put(word, count+1);
          }             
          else
              map.put(word, 1);
      }
  
      MyComparator comp= new MyComparator(map);
      Map&lt;String,Integer&gt; newMap= new TreeMap(comp);
      newMap.putAll(map);
      Iterator it= newMap.entrySet().iterator();
      while (it.hasNext())
      {
          Map.Entry pairs = (Map.Entry) it.next();
          System.out.println("Key  "+pairs.getKey()+"-- value"+pairs.getValue());
      }
  
      return arr;
  }
  </code></pre>
  
  <p>Here's the comparator</p>
  
  <pre><code>package samplecodes;
  
  import java.util.Comparator;
  import java.util.Map;
  
  public class MyComparator implements Comparator {
  
      Map map;
  
      public MyComparator(Map map){
          this.map=map;
      }
  
      @Override
      public int compare(Object o1, Object o2) {
          return ((Integer)map.get(o1) &gt;(Integer)map.get(o2)? (Integer)map.get(o1):(Integer)map.get(o2));
      }
  
  }
  </code></pre>
  
  <p>And the output is of the form</p>
  
  <pre><code>me-2
  hello-3
  i-3
  </code></pre>