How to Split odd and even numbers and sum of both

2019-02-15 23:55发布

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

3条回答
神经病院院长
2楼-- · 2019-02-16 00:14

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楼-- · 2019-02-16 00:15

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.

查看更多
老娘就宠你
4楼-- · 2019-02-16 00:15

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
查看更多
登录 后发表回答