title: TreeMap sort is not working on equal values
body: <p>I have written a method that sorts the <code>TreeMap</code> by its values</p>
  
  <pre><code>public TreeMap&lt;String, Integer&gt; sortByValues(final TreeMap&lt;String, Integer&gt; map) {
          Comparator&lt;String&gt; valueComparator =  new Comparator&lt;String&gt;() {
              public int compare(String k1, String k2) {
                  int compare = map.get(k1).compareTo(map.get(k2));
                  return compare;
              }
          };
          Map&lt;String, Integer&gt; sortedByValues = new TreeMap&lt;String, Integer&gt;(valueComparator);
          sortedByValues.putAll(map);
          return sortedByValues;
      }
  </code></pre>
  
  <p>The above method works fine in normal case but fails when there is a duplicate value present in the TreeMap. Any duplicate value entry is removed from the Map.After googling it I found the solution as</p>
  
  <pre><code>public Map&lt;String, Integer&gt; sortByValuesTree(final Map&lt;String, Integer&gt; map) {
          Comparator&lt;String&gt; valueComparator =  new Comparator&lt;String&gt;() {
              public int compare(String k1, String k2) {
                  int compare = map.get(k1).compareTo(map.get(k2));
                  if (compare == 0) return 1;
                  else return compare;
              }
          };
          Map&lt;String, Integer&gt; sortedByValues = new TreeMap&lt;String, Integer&gt;(valueComparator);
          sortedByValues.putAll(map);
          return sortedByValues;
      }
  </code></pre>
  
  <p>The above works fine but I am not able to understand why first method didn't work. Why did it remove duplicate value entry? Can someone please let me know</p>