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