提问者:小点点

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


如何拆分奇数和偶数和和都在一个集合使用流方法的Java

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

共3个答案

匿名用户

您可以使用Collectors.分隔符来做您想要的:

Map<Boolean, Integer> 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<Integer> 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<Integer> evenFunc = (a) -> a%2 == 0;
    Predicate<Integer> oddFunc = evenFunc.negate();

    int evenSum = lst.stream().filter(evenFunc).mapToInt((a) -> a).sum();
    int oddSum = lst.stream().filter(oddFunc).mapToInt((a) -> a).sum();

    Map<String, Integer> oddsAndEvenSumMap = new HashMap<>();
    oddsAndEvenSumMap.put("EVEN", evenSum);
    oddsAndEvenSumMap.put("ODD", oddSum);

    System.out.println(oddsAndEvenSumMap);
  }
}

我所做的一个改变是使生成的Map成为Map

匿名用户

    List<Integer> numberList = Arrays.asList(1,3,4,60,12,22,333456,1239);
    Map<Boolean, List<Integer>> evenOddNumbers = numberList.stream()
            .collect(Collectors.partitioningBy( x -> x%2 == 0));
    System.out.println(evenOddNumbers);

输出:

{false=[1,3,1239], true=[4,60,12,22,333456]}

如果想把它分开,使用下面的一个:

List<Integer> evenNums = partitions.get(true);
List<Integer> oddNums = partitions.get(false);