Reputation: 531
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
Upvotes: 2
Views: 3602
Reputation: 137064
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();
Upvotes: 8