I am currently writing a program that lists numbers the user enters and totals the sums of all, even and odd using an array. When calculating the sum of the even numbers the odd numbers in the list should be removed. Here is the code:
I am able to add the even numbers but I am having trouble remove the odd numbers. Any tips?
Campbell Ritchie wrote:Can you partition the stream into two and add odd and even in one pass?
Not easily. Since you can only call one terminal operation per stream, you'd have to extend IntStream with a reduceIf(IntPredicate, int, IntBinaryOperator) method, that returns a ConditionallyReducingIntStream, which has an elseReduce(int, IntBinaryOperator) method, which returns an IntStream of reduced values on which you can perform the terminal operation.
Otherwise you would end up with some horror like this?I presume you have come across the bitwise and operator as an alternative to the remainder operator? Once you have tried Stream operations with int arrays, you will start cursing the very existence of arrays of primitives. I am assuming that numbers is a List<Integer>, in which case how do you get Integer::parseInt to compile? I am allowing the compiler to do its own unnboxing rather than trying to do it explicitly with map methods.
Can you use Collectors#groupingBy to create a Map<Integer, Integer> with remainders and totals?