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

15,892

Solution 1

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.

Solution 2

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.

Share:
15,892
Bhaumik Thakkar
Author by

Bhaumik Thakkar

Updated on June 11, 2022

Comments

  • Bhaumik Thakkar
    Bhaumik Thakkar almost 2 years

    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);
            }
        }
    }
    
  • David Conrad
    David Conrad about 8 years
    An enum would be even better than strings.
  • Novice User
    Novice User over 5 years
    How can it be changed to return the count of odd vs even instead of the sum? Collectors.counting() does not seem to work.
  • Tagir Valeev
    Tagir Valeev over 5 years
    @NoviceUser counting() returns long, so you need to change to Map<Boolean, Long>