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 : [29,32,28,-1,33,-1,44]
Expected Result : [29,32,28,0,33,0,44]
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);
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