How to perform some mathematical operation on some specific elements of a list using java 8?

  • A+

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 = -> x > 0).map(x -> x - 1).collect(Collectors.toList()); // -> x - 1).collect(Collectors.toList()); //This is giving error ->x.); //How to use this in this case 

Actual Result : [29,32,28,-1,33,-1,44]

Expected Result : [29,32,28,0,33,0,44]     .map(x -> x == 0 ? x : x - 1)     .collect(Collectors.toList()); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: