Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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 : [29,32,28,-1,33,-1,44]

Expected Result : [29,32,28,0,33,0,44]

like image 795
Vaibhav_Sharma Avatar asked Jan 14 '19 13:01

Vaibhav_Sharma


3 Answers

list.stream()
    .map(x -> x == 0 ? x : x - 1)
    .collect(Collectors.toList());
like image 76
Eugene Avatar answered Nov 13 '22 02:11

Eugene


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]
like image 5
ByeBye Avatar answered Nov 13 '22 01:11

ByeBye


A non-stream version is using of replaceAll

list.replaceAll(x -> x != 0 ? x - 1 : x);
like image 2
Hadi J Avatar answered Nov 13 '22 03:11

Hadi J