title: Map values in Collectors.groupingBy()
body: <p>For the sake of this example, let's assume I have a simple type <code>Tuple</code> with two attributes:</p>
  
  <pre><code>interface Tuple&lt;T, U&gt; {
      T getFirst();
      U getSecond();
  }
  </code></pre>
  
  <p>Now I want to transform a collection of <code>(first, second)</code> tuples into a map which maps each <code>first</code> value to a set of all <code>second</code> values contained in tuples with that specific <code>first</code> value. The method <code>groupSecondByFirst()</code> shows a possible implementation doing what I want:</p>
  
  <pre><code>&lt;T, U&gt; Map&lt;T, Set&lt;U&gt;&gt; groupSecondByFirst(Set&lt;Tuple&lt;T, U&gt;&gt; tuples) {
      Map&lt;T, Set&lt;U&gt;&gt; result = new HashMap&lt;&gt;();
  
      for (Tuple&lt;T, U&gt; i : tuples) {
          result.computeIfAbsent(i.getFirst(), x -&gt; new HashSet&lt;&gt;()).add(i.getSecond());
      }
  
      return result;
  }
  </code></pre>
  
  <p>If the input was <code>[(1, "one"), (1, "eins"), (1, "uno"), (2, "two"), (3, "three")]</code> the output would be <code>{ 1 = ["one", "eins", "uno"], 2 = ["two"], 3 = ["three"] }</code></p>
  
  <p>I would like to know whether and how I can implement this using the streams framework. The best I got is the following expression, which returns a map which contains the full tuple as values and not just their <code>second</code> elements:</p>
  
  <pre><code>Map&lt;T, Set&lt;Tuple&lt;T, U&gt;&gt;&gt; collect = tuples.stream().collect(
      Collectors.groupingBy(Tuple::getFirst, Collectors.toSet()));
  </code></pre>