How can I store unfiltered data in a collection in Java 8 Streaming API?
My input sequence: [1,2,3,4,5]
The result should be: [1,12,3,14,5]
These even numbers are incremented by 10, but the odd numbers remain intact.
Here's what I've tried:
public static List<Integer> incrementEvenNumbers(List<Integer> arrays){
List<Integer> temp =
arrays.stream()
.filter(x->x%2==0)
.map(i -> i+10)
.collect(Collectors.toList());
return temp;
}
when i call this method,
System.out.println(incrementEvenNumbers(Arrays.asList(1,2,3,4,5)));
I receive [12, 14]
. I am wondering how to include values ββinstead of filtered
but map
should not be applied to it.
source to share
You can use the ternary operator with map
such that the function you use is either an identifier for odd values ββor one that increments values ββby 10 for even values:
List<Integer> temp = arrays.stream()
.map(i -> i % 2 == 0 ? i+10 : i)
.collect(Collectors.toList());
The problem, as you've seen, is that the filter will remove items, so when a terminal operation is called, they will be filtered by the predicate.
Note that if you don't want to modify the list in-place, you can use replaceAll
directly, since you are doing a mapping from type T to T.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.replaceAll(i -> i % 2 == 0 ? i+10 : i); //[1, 12, 3, 14, 5]
source to share