Based on some conditions I want to perform some operation on a specific element of a list only.
I have a list of integers like this:
List<Integer> list = new ArrayList(Arrays.asList(30,33,29,0,34,0,45));
and I want to subtract 1 from each element EXCEPT 0.
I have tried some approaches like by applying the filter of Java 8 but it removed the zero values from the list. I tried to apply other methods provided for streams API like
foreach() or .findFirst(),.findAny() but it didn't work.
List<Integer> list2 = list.stream().filter(x -> x > 0).map(x -> x - 1).collect(Collectors.toList()); //list.stream().findFirst().ifPresent(x -> x - 1).collect(Collectors.toList()); //This is giving error list.stream().forEach(x ->x.); //How to use this in this case
Actual Result :
Expected Result :
list.stream() .map(x -> x == 0 ? x : x - 1) .collect(Collectors.toList());