how can I Split odd and even numbers and sum both in collection using Stream method of java-8 ??
public class SplitAndSumOddEven {
public static void main(String[] args) {
// Read the input
try (Scanner scanner = new Scanner(System.in)) {
// Read the number of inputs needs to read.
int length = scanner.nextInt();
// Fillup the list of inputs
List<Integer> inputList = new ArrayList<>();
for (int i = 0; i < length; i++) {
inputList.add(scanner.nextInt());
}
// TODO:: operate on inputs and produce output as output map
Map<Boolean, Integer> oddAndEvenSums = inputList.stream(); \\here I want to split odd & even from that array and sum of both
// Do not modify below code. Print output from list
System.out.println(oddAndEvenSums);
}
}
}
It's easiest (and cleanest) to do it in two separate stream operations, like such:
One change I did make was making the resultant Map a
Map<String,Integer>
instead ofMap<Boolean,Integer>
. It's vey unclear what a key oftrue
in the latter Map would represent, whereas string keys are slightly more effective. It's unclear why you need a map at all, but I'll assume that goes on to a later part of the problem.You can use
Collectors.partitioningBy
which does exactly what you want:The resulting map contains sum of even numbers in
true
key and sum of odd numbers infalse
key.Try this.