title: In Java8, when will the merge function be triggered in Collectors.toMap?
body: <p>I want to transform a <code>Hashmap&lt;String,Long&gt;</code> to a <code>Treemap</code>, in order to sort its key by string.length (I can't simply use <code>treemap.addAll</code> because I have may other logic when insert and I want to use java8)</p>
  
  <p>The code is below. But when keys with same length exist in the initial Hashmap, it will trigger the merge function which throws Exception(I intent to do it because there won't be same string in my case). I wonder why the merge function be triggered since the JavaDoc of toMap() says "If the <strong>mapped keys</strong> contains duplicates (according to Object#equals(Object)), the value mapping function is applied to each equal element, and results are merged using the provided merging function."  I think that in my code the  "mapped keys" should be the entry in hashMap mapped by <code>Entry::getKey</code> but not <code>string.length()</code> in the TreeMap comparator. i.e. "abc" != "def". So it shouldn't trigger the merge. But?? What the hell?</p>
  
  <pre><code>public class TestToMap {
  
      public static Map&lt;String, Long&gt; map1 = new HashMap&lt;String, Long&gt;() {
          {
              put("abc", 123L);
              put("def", 456L);
          }
      };
  
      public static void main(String[] args) {
          Map&lt;String, Long&gt; priceThresholdMap = map1.entrySet().stream()
              .collect(Collectors.toMap(Entry::getKey,
                                        Entry::getValue,
                                        throwingMerger(),
                                        () -&gt; new TreeMap&lt;String, Long&gt;(
                                            (a, b) -&gt; {
                                                return a.length() - b.length();
                                            }))); // this will trigger merge function, why?
          //() -&gt; new TreeMap&lt;String, Long&gt;(Comparator.comparingInt(String::length).thenComparing(String::compareTo))));  // but this won't trigger merge function 
  
      }
  
      private static &lt;T&gt; BinaryOperator&lt;T&gt; throwingMerger() {
          return (u, v) -&gt; {
              throw new IllegalStateException(String.format("priceThresholdMap has duplicate v1 %s,v2 %s", u, v));
          };
      }
  }
  </code></pre>