如何使用Stream拆分集合中的奇数和偶数以及两者的总和

我如何使用java-8的Stream方法拆分奇数和偶数并在集合中求和?

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

您可以使用Collectors.partitioningBy ,它可以完全满足您的需求:

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

生成的映射包含true密钥中的偶数和false密钥中奇数之和的总和。

在两个独立的流操作中执行它是最简单的(也是最干净的),例如:

 public class OddEvenSum { public static void main(String[] args) { List 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 evenFunc = (a) -> a%2 == 0; Predicate oddFunc = evenFunc.negate(); int evenSum = lst.stream().filter(evenFunc).mapToInt((a) -> a).sum(); int oddSum = lst.stream().filter(oddFunc).mapToInt((a) -> a).sum(); Map oddsAndEvenSumMap = new HashMap<>(); oddsAndEvenSumMap.put("EVEN", evenSum); oddsAndEvenSumMap.put("ODD", oddSum); System.out.println(oddsAndEvenSumMap); } } 

我做的一个改变是使得结果Map为Map而不是Map 。 很true ,后一个Map中的true关键字代表什么,而字符串键更有效。 目前还不清楚为什么你需要一张地图,但我会假设这会继续问题的后期部分。

尝试这个。

  List 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