title: Java 8: grouping a collection by a field and flatten and join a collection as mapped value using stream?
body: <p>My class has two fields:</p>
  
  <ul>
  <li><code>MyKey</code> - the key that I want to group by</li>
  <li><code>Set&lt;MyEnum&gt;</code> - the set that I want to be flattened and merged.</li>
  </ul>
  
  <p>I have a list of such objects, and what I want is to obtain a <code>Map&lt;MyKey, Set&lt;MyEnum&gt;</code> of which the value is joined from all myEnums of the objects with this key.</p>
  
  <p>For example, if I have three objects:</p>
  
  <ol>
  <li><code>myKey: key1, myEnums: [E1]</code></li>
  <li><code>myKey: key1, myEnums: [E2]</code></li>
  <li><code>myKey: key2, myEnums: [E1, E3]</code></li>
  </ol>
  
  <p>The expected result should be:</p>
  
  <p><code>key1 =&gt; [E1, E2], key2 =&gt; [E1, E3]</code></p>
  
  <p>I came up with this code:</p>
  
  <pre><code>Map&lt;MyKey, Set&lt;MyEnum&gt;&gt; map = myObjs.stream()
          .collect(Collectors.groupingBy(
                  MyType::getMyKey,
                  Collectors.reducing(
                          new HashSet&lt;MyEnum&gt;(),
                          MyType::getMyEnums,
                          (a, b) -&gt; {
                              a.addAll(b);
                              return a;
                          })));
  </code></pre>
  
  <p>There're two problems with it:</p>
  
  <ol>
  <li><p>The <code>HashSet</code> inside the reducing seems to be shared between all keys. That being said the actual run result of the above example is <code>key1 =&gt; [E1, E2, E3], key2 =&gt; [E1, E2, E3]</code>. Why is it the case?</p></li>
  <li><p>Even if this code works, it looks ugly especially at the part of reducing that I have to handle the logic of constructing the joined collection manually. Is there a better way of doing this?</p></li>
  </ol>
  
  <p>Thank you!</p>