title: Sorting map by value in Java
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>Here's my handiwork:</p>
  
  <pre><code>ArrayList&lt;Map.Entry&lt;Integer, Integer&gt;&gt; suits = new ArrayList&lt;Map.Entry&lt;Integer, Integer&gt;&gt;();
  suits.add(new AbstractMap.SimpleEntry(0, 3));
  suits.add(new AbstractMap.SimpleEntry(1, 5));
  suits.add(new AbstractMap.SimpleEntry(2, 1));
  suits.add(new AbstractMap.SimpleEntry(3, 3));
  Collections.sort(suits, new Comparator&lt;Map.Entry&lt;Integer, Integer&gt;&gt;() {
    @Override
    public int compare(Entry&lt;Integer, Integer&gt; e1, Entry&lt;Integer, Integer&gt; e2) {
      if (e1.getValue() &gt; e2.getValue())
        return 1;
      else if (e1.getValue() &lt; e2.getValue())
        return -1;
      else if (e1.getKey() &gt; e2.getKey())
        return 1;
      else if (e1.getKey() &lt; e2.getKey())
        return -1;
      else
        return 0;
    }
  });
  </code></pre>
  
  <p>It works (at least on the simple test case I included). It's intended to sort a hand of cards by number of cards (for example 3 spades, 5 hearts, 5 diamonds, 6 clubs), then proceed to do stuff with the suits we have less cards of (3 spades).</p>
  
  <p>I have seen this problem of sorting a Map by value is a frequent one, and I had a little trouble understanding some of the answers provided elsewhere as I have absolutely no formal training in coding, nor in Java - so I made my own.
  Is anything blatantly wrong in this code? If it's not worth a daily WTF, it's good enough for me.</p>
  
  <p>Thanks.</p>