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

Bha*_*kar 1 java collections lambda java-8 java-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<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);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Tag*_*eev 17

您可以使用Collectors.partitioningBy哪个完全符合您的要求:

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

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

  • @NoviceUser count() 返回long,所以需要改成`Map&lt;Boolean, Long&gt;` (2认同)

Msh*_*nik 5

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

我所做的一项更改是使生成的 Map aMap<String,Integer>而不是Map<Boolean,Integer>. 很不清楚true后一个 Map 中的键代表什么,而字符串键稍微更有效。目前还不清楚为什么你需要一张地图,但我认为这会继续到问题的后面部分。