I need to modify a list on int as it follows:
Here is my attempt:
list.stream()
.filter(val -> val.getValue() == 10)
.map(val -> {
val.doubleValue();
return val;
})
.forEach(System.out::println);
The problem is that I'm filtering the elements, while I would like to keep them all and just modify the ones == 0.
EDIT: the list is composed of elements of MyType
, defined as it follows:
public class MyType {
private int val;
public MyType(int v){
this.val = v;
}
public void doubleVal(){
val*val;
}
public int getValue(){
return val;
}
}
Any suggestion?
Don't use filter
. Put all the logic in map
:
list.stream()
.map(val -> val == 10 ? 2*val : val)
.forEach(System.out::println);
EDIT : I simplified the code after your clarification that the elements of the list are Integer
s. Note that the original List
remains unchanged.
Assuming that your list is a list of Val, and Val is something like
class Val {
private int v;
public Val(int v) {
this.v = v;
}
int getValue() {
return v;
}
public void doubleValue() {
v *= 2;
}
}
then
public static void main(String ... args ) {
List<Val> ints = Arrays.asList(new Val(1), new Val(5), new Val(10), new Val(2));
ints.stream().map((v) -> {
if (v.getValue() == 10) v.doubleValue(); return v;
}).forEach(v -> System.out.println(v.getValue()));
}
will do the trick.
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