title: Java 8 Lambda (grouping and reducing in a single step)
body: <p>Say I have a List of Pair objects, </p>
  
  <pre><code>List&lt;Pair&lt;A,B&gt;&gt; listOfPairs = //some list of pairs ; 
  </code></pre>
  
  <p>I would like to group this list into a <code>Map&lt;A,Set&lt;B&gt;&gt;</code>.</p>
  
  <p>Currently, I can do this in two steps. The first step groups by A, and returns a 
  <code>Map&lt;A,Set&lt;Pair&lt;A,B&gt;&gt;</code> as follows:</p>
  
  <pre><code>   Map&lt;A,Set&lt;Pair&lt;A,B&gt;&gt; intermediateStep =   listOfPairs.stream().collect(Collectors.groupingBy((Pair::getLeft), Collectors.toSet()));
  </code></pre>
  
  <p>I then  stream the entryset of the map above and collect them into the desired end result, mainly by mapping each Pair object to its B value, and collecting them to a set:</p>
  
  <pre><code> Map&lt;A, Set&lt;B&gt;&gt; finalResult= intermediateStep.entrySet().stream().collect(Collectors.toMap(e -&gt; e.getKey(), e -&gt; e.getValue().stream().map(Pair::getRight).collect(Collectors.toSet())));
  </code></pre>
  
  <p>Is there a better way to achieve the desired result, perhaps in one step? In other words, the intermediate step mentioned above groups by A, but the right side of the grouping returns the entire Pair object. I'd like to group by A and point A to the set of its associated Bs in one step.</p>
  
  <p>(I know that just because I <em>could</em> do it in one step, doesn't mean I should, because readability might suffer, but I'm curious.)</p>
  
  <p>Thanks! </p>