How to split odd and even numbers and sum of both in a collection using Stream
Asked Answered
C

6

7

How can I split odd and even numbers and sum both in a collection using stream methods 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);
        }
    }
}
Cleancut answered 22/1, 2016 at 5:10 Comment(2)
Please provide some code to show what you have done so far. what have you attempted. where are you getting suck atAdelladella
pls see updated question now! @MarquisBlountCleancut
D
32

You can use Collectors.partitioningBy which does exactly what you want:

Map<Boolean, Integer> result = inputList.stream().collect(
       Collectors.partitioningBy(x -> x%2 == 0, Collectors.summingInt(Integer::intValue)));

The resulting map contains sum of even numbers in true key and sum of odd numbers in false key.

Deportment answered 22/1, 2016 at 7:7 Comment(2)
How can it be changed to return the count of odd vs even instead of the sum? Collectors.counting() does not seem to work.Brunswick
@NoviceUser counting() returns long, so you need to change to Map<Boolean, Long>Deportment
B
5

It's easiest (and cleanest) to do it in two separate stream operations, like such:

public class OddEvenSum {

  public static void main(String[] args) {

    List<Integer> lst = ...; // Get a list however you want, for example via scanner as you are. 
                             // To test, you can use Arrays.asList(1,2,3,4,5)

    Predicate<Integer> evenFunc = (a) -> a%2 == 0;
    Predicate<Integer> oddFunc = evenFunc.negate();

    int evenSum = lst.stream().filter(evenFunc).mapToInt((a) -> a).sum();
    int oddSum = lst.stream().filter(oddFunc).mapToInt((a) -> a).sum();

    Map<String, Integer> oddsAndEvenSumMap = new HashMap<>();
    oddsAndEvenSumMap.put("EVEN", evenSum);
    oddsAndEvenSumMap.put("ODD", oddSum);

    System.out.println(oddsAndEvenSumMap);
  }
}

One change I did make was making the resultant Map a Map<String,Integer> instead of Map<Boolean,Integer>. It's vey unclear what a key of true 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.

Bottom answered 22/1, 2016 at 5:46 Comment(1)
An enum would be even better than strings.Darbies
R
1
    List<Integer> numberList = Arrays.asList(1,3,4,60,12,22,333456,1239);
    Map<Boolean, List<Integer>> evenOddNumbers = numberList.stream()
            .collect(Collectors.partitioningBy( x -> x%2 == 0));
    System.out.println(evenOddNumbers);

Output:

{false=[1, 3, 1239], true=[4, 60, 12, 22, 333456]}

and if want to separate it out the use below one:

List<Integer> evenNums = partitions.get(true);
List<Integer> oddNums = partitions.get(false);
Rad answered 25/7, 2022 at 14:19 Comment(0)
B
0

Easiest way to find even numbers from list and then performing addition of even numbers using Stream :

int number = l.stream().filter(n->n%2==0).mapToInt(n -> n).sum();
        System.out.println(number);
    
    
Blub answered 22/2, 2023 at 14:7 Comment(0)
P
0

Below is the two use case of separating the ODD and EVEN numbers from an Integer array -

..............................................................................

    int[] arr = {45,23,6,8,9,2};
Map<Boolean, List<Integer>> strm = Arrays.stream(arr).boxed().collect(Collectors.partitioningBy(i -> i%2 == 0));  
System.out.println(strm);  
// Output - {false=[45, 23, 9], true=[6, 8, 2]}

System.out.println(Arrays.stream(arr).mapToObj(ob -> Integer.valueOf(ob)).collect(Collectors.groupingBy(t-> t%2 == 0 ?"ODD" : "EVEN")));
// Output - {EVEN=[6, 8, 2], ODD=[45, 23, 9]}
Platitudinous answered 10/8, 2023 at 11:34 Comment(0)
R
0

You can try the code snippet

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);

// Sum of even numbers
int evenSum = numbers.stream()
  .filter(num -> num % 2 == 0)
  .mapToInt(Integer::intValue)
  .sum();

System.out.println("Sum of Even numbers: " + evenSum);

// Sum of odd numbers
int oddSum = numbers.stream()
  .filter(num -> num % 2 != 0)
  .mapToInt(Integer::intValue)
  .sum();

 System.out.println("Sum of Odd numbers: " + oddSum);
Rarefied answered 21/3 at 18:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.