I wanna do some thing like this :
List<Integer> list = [1,2,1,3];
for (each : list) {
if (each == 1) {
remove (each);
} else {
each = 4;
}
}
after the loop the list is supposed to be [4,4].
I have tried the following codes :
List<String> list = new ArrayList<>(Arrays.asList("1", "2", "1", "3"));
for (String i : list) {
if (i.equals("1")) {
i = "4";
}
}
But it doesn't change the value, the list is [2,3].
List<Integer> list = [1,2,1,3];
for (int i = 0; i< list.size(); i++) {
//do something to replace the element
}
This can replace the element but can not remove the element.
The only way I can come up with is to remove the elements in one loop, and replace the element in another loop, how can I do both in just one loop?