title: Grouping a range of integers to the answer of a function
body: <p>For a range of integers, I would like to apply an ("expensive") operation, filter out only those integers with interesting answers, then group on the answer.</p>
  
  <p>This first snippet works, but it duplicates the operation ("modulus 2") both in code and computation:</p>
  
  <pre><code>IntStream.range(1, 10).boxed()
           .filter(p -&gt; (p % 2 != 0))                     // Expensive computation
           .collect(Collectors.groupingBy(p -&gt; (p % 2))); // Same expensive
                                                          // computation!
  
  // {1=[1, 3, 5, 7, 9]} (Correct answer)
  </code></pre>
  
  <p>I tried mapping to the answer first, then filter, then group - but the initial Integer of course gets lost along the way:</p>
  
  <pre><code>IntStream.range(1, 10).boxed()
           .map(p -&gt; p % 2)                        // Expensive computation
           .filter(p -&gt; p != 0)
           .collect(Collectors.groupingBy(p -&gt; p));
  
  // {1=[1, 1, 1, 1, 1]} (Of course, wrong answer)
  </code></pre>
  
  <p>I would like to map to a tuple or something like that, but haven't figured out a clean way to do it.</p>