![](/img/trans.png)
[英]Using one stream delete from a list odd integers if their sum is odd, delete even integers if the sum is even
[英]How to split odd and even numbers and sum of both in a collection using Stream
如何使用 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
來滿足您的需求:
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<String,Integer>
而不是Map<Boolean,Integer>
。 后一個 Map 中的true
鍵代表什么還不清楚,而字符串鍵稍微更有效。 目前還不清楚為什么你需要一張地圖,但我認為這會繼續到問題的后面部分。
嘗試這個。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
int[] a = list.stream()
.map(n -> n % 2 == 0 ? new int[] {n, 0} : new int[] {0, n})
.reduce(new int[] {0, 0}, (x, y) -> new int[] {x[0] + y[0], x[1] + y[1]});
System.out.println("even sum = " + a[0]); // -> even sum = 20
System.out.println("odd sum = " + a[1]); // -> odd sum = 25
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.