本文介绍了如何使用Stream在集合中拆分奇数和偶数以及两者的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java 8的流方法分解成奇数和偶数并求和?

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

推荐答案

您可以使用完全符合您的要求:

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

生成的映射在 true 键中包含偶数和,在 false 键中包含奇数.

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

这篇关于如何使用Stream在集合中拆分奇数和偶数以及两者的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 05:04