简体   繁体   中英

Java 8 sum or subtract depending on even odd

Suppose I have a list of int

1,2,3,4,5,6,7,8,9,10

How can do add if the number is even and subtract if the number is odd? I can do this using a for loop but I want to know how I can do that using new Java 8 feature like stream and filter

A possible solution would be to map each value in the array to itself if it's even and to its opposite if it's odd. That way, by summing the result, you will have added all even numbers and subtracted all odd ones.

You can retrieve an IntStream from an int array with Arrays.stream(array) , then use map to transform the even and odd values and finally call sum to sum all values.

Sample code:

int[] array = { 1,2,3,4,5,6,7,8,9,10 };
int sum = Arrays.stream(array).map(i -> i % 2 == 0 ? i : -i).sum();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM