How to perform some mathematical operation on some specific elements of a list using java 8?
list.stream()
.map(x -> x == 0 ? x : x - 1)
.collect(Collectors.toList());
In the example, you can use Math.max
method:
list.stream()
.map(x -> Math.max(0, x - 1))
.collect(Collectors.toList());
In your case:
list.stream() // 1,2,0,5,0
.filter(x -> x > 0) // 1,2,5
.map(x -> x - 1) // 0,1,4
.collect(Collectors.toList()); // will return list with three elements [0,1,4]
A non-stream version is using of replaceAll
list.replaceAll(x -> x != 0 ? x - 1 : x);