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
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]