如何拆分奇数,偶数和两个和在使用流的集合 [英] How to Split odd and even numbers and sum of both in collection using Stream

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

问题描述

如何使用Java-8的Stream方法拆分奇数和偶数以及两者的总和?

  class SplitAndSumOddEven {

public static void main(String [] args){

//读取输入
try(Scanner scanner = new Scanner )){
//读取需要读取的输入数。
int length = scanner.nextInt();
//填充输入列表
List< Integer> inputList = new ArrayList<>();
for(int i = 0; i inputList.add(scanner.nextInt());
}
// TODO ::对输入进行操作并且产生输出作为输出映射
Map< Boolean,Integer> oddAndEvenSums = inputList.stream(); \\我想分裂奇怪&甚至从那个数组和两者的和
//不要修改下面的代码。从列表中打印输出
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 键中的奇数的总和。


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

解决方案

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆