gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:34:26 26 4
gpt4 key购买 nike

如何使用 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);
}
}
}

最佳答案

您可以使用 Collectors.partitioningBy这正是你想要的:

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

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

关于java - 如何使用 Stream 拆分集合中的奇数和偶数以及两者的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34939425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com