java - How to Split odd and even numbers and sum of both in collection using Stream -
how can split odd , numbers , sum both in collection using stream method of java-8 ??
public class splitandsumoddeven { public static void main(string[] args) { // read input try (scanner scanner = new scanner(system.in)) { // read number of inputs needs read. int length = scanner.nextint(); // fillup list of inputs list<integer> inputlist = new arraylist<>(); (int = 0; < length; i++) { inputlist.add(scanner.nextint()); } // todo:: operate on inputs , produce output output map map<boolean, integer> oddandevensums = inputlist.stream(); \\here want split odd & array , sum of both // not modify below code. print output list system.out.println(oddandevensums); } } }
you can use collectors.partitioningby
want:
map<boolean, integer> result = inputlist.stream().collect( collectors.partitioningby(x -> x%2 == 0, collectors.summingint(integer::intvalue)));
the resulting map contains sum of numbers in true
key , sum of odd numbers in false
key.
Comments
Post a Comment