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

那年仲夏 提交于 2019-12-19 04:54:09

问题


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);
    }
}
}

回答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.




回答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.




回答3:


Try this.

    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    int[] a = list.stream()
        .map(n -> n % 2 == 0 ? new int[] {n, 0} : new int[] {0, n})
        .reduce(new int[] {0, 0}, (x, y) -> new int[] {x[0] + y[0], x[1] + y[1]});
    System.out.println("even sum = " + a[0]);   // -> even sum = 20
    System.out.println("odd sum = " + a[1]);    // -> odd sum = 25


来源:https://stackoverflow.com/questions/34939425/how-to-split-odd-and-even-numbers-and-sum-of-both-in-collection-using-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!