My Input Sequence is : [1,2,3,4,5]
Result should be : [1,12,3,14,5]
That is even numbers are incremented by 10, but odd values are left intact.
Here is what I 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 get [12, 14]
. I am wondering how to include the values not filtered
to seep in but the map
should not be applied for it.
You can use a ternary operator with map
, so that the function you apply is either the identity for odd values, or the one that increments the value 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 saw, is that filter will remove the elements so when a terminal operation will be called, they will be filtered by the predicate.
Note that if you don't care modifying the list in place, you can use replaceAll
directly, as you are doing a mapping from a 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With