【问题标题】:How to split odd and even numbers and sum of both in a collection using Stream如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和
【发布时间】:2016-04-28 14:57:55
【问题描述】:

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

【问题讨论】:

  • 请提供一些代码来展示你到目前为止所做的事情。你有什么尝试。你在哪里搞砸了
  • 请立即查看更新的问题! @MarquisBlount

标签: java collections lambda java-8 java-stream


【解决方案1】:

在两个单独的流操作中做到这一点是最简单(也是最干净)的,例如:

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&lt;String,Integer&gt; 而不是 Map&lt;Boolean,Integer&gt;。目前还不清楚后一个 Map 中 true 的键代表什么,而字符串键稍微更有效。目前还不清楚你为什么需要一张地图,但我认为这会延续到问题的后面部分。

【讨论】:

  • enum 会比字符串更好。
【解决方案2】:

您可以使用 Collectors.partitioningBy 来满足您的需求:

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

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

【讨论】:

  • 如何更改它以返回奇数与偶数的计数而不是总和? Collectors.counting() 似乎不起作用。
  • @NoviceUsercounting() 返回long,所以需要改成Map&lt;Boolean, Long&gt;
猜你喜欢
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 2021-10-27
相关资源
最近更新 更多