title: TreeMap sort by value
body: <p>I want to write a comparator that will let me sort a TreeMap by value instead of the default natural ordering.</p>
  
  <p>I tried something like this, but can't find out what went wrong:</p>
  
  <pre><code>import java.util.*;
  
  class treeMap {
      public static void main(String[] args) {
          System.out.println("the main");
          byValue cmp = new byValue();
          Map&lt;String, Integer&gt; map = new TreeMap&lt;String, Integer&gt;(cmp);
          map.put("de",10);
          map.put("ab", 20);
          map.put("a",5);
  
          for (Map.Entry&lt;String,Integer&gt; pair: map.entrySet()) {
              System.out.println(pair.getKey()+":"+pair.getValue());
          }
      }
  }
  
  class byValue implements Comparator&lt;Map.Entry&lt;String,Integer&gt;&gt; {
      public int compare(Map.Entry&lt;String,Integer&gt; e1, Map.Entry&lt;String,Integer&gt; e2) {
          if (e1.getValue() &lt; e2.getValue()){
              return 1;
          } else if (e1.getValue() == e2.getValue()) {
              return 0;
          } else {
              return -1;
          }
      }
  }
  </code></pre>
  
  <p>I guess what am I asking is: Can I get a <code>Map.Entry</code> passed to the comparator?</p>