title: Comparator creates duplicates in TreeMap
body: <p>I would like to sort my <code>HashMap</code> (or <code>TreeMap</code>) by values. I kind of achieved this by creating a custom <code>Comparator</code> that sorts after value. However whenever I put in all my entries from the <code>HashMap</code> again I get duplicates.</p>
  
  <p>How can I sort by values without creating duplicates?</p>
  
  <p><strong>CODE</strong></p>
  
  <pre><code>public class Test {
      public static void main(String[] args) {
  
          HashMap&lt;Integer, String&gt; hMap = new HashMap&lt;Integer, String&gt;();
          ValueComparator vc = new ValueComparator(hMap);
          TreeMap&lt;Integer, String&gt; tMap = new TreeMap&lt;Integer, String&gt;(vc);
  
          hMap.put(0, "b");
          hMap.put(1, "c");
          hMap.put(2, "a");
          tMap.putAll(hMap);
          tMap.putAll(hMap);
  
          for (Map.Entry&lt;Integer, String&gt; entry : tMap.entrySet()) {
              System.out.println(entry.getKey() + " " + entry.getValue());
          }
      }
  }
  
  class ValueComparator implements Comparator&lt;Integer&gt; {
      Map&lt;Integer, String&gt; base;
  
      public ValueComparator(Map&lt;Integer, String&gt; base) {
          this.base = base;
      }
  
      public int compare(Integer a, Integer b) {
          if (base.get(a).charAt(0) &gt;= base.get(b).charAt(0))
               return 1;
          else return -1;
      }
  }
  </code></pre>
  
  <p><strong>OUTPUT</strong></p>
  
  <pre><code>2 a
  2 a
  0 b
  0 b
  1 c
  1 c
  </code></pre>