How to split odd and even numbers and sum of both in a collection using Stream(如何使用 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);
}
}
}
推荐答案
你可以使用 Collectors.partitioningBy 完全符合您的要求:
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 在集合中拆分奇数和偶数以及两者的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
