0

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?

2 Answers 2

1

Your following code doesn't work:

for (String i : list) {
    if (i.equals("1")) {
        i = "4";
    }
}

because you're replacing the value of String i instead of the selected item of list.

You need to use set method:

for (int i = 0; i < list.size(); i++) {
    String item = list.get(i);
    if (item.equals("1")) {
        list.set(i, "4");
    }
}

UPDATE

If you want to remove and change the item in one loop, you need to use listIterator and change for loop with while loop:

ListIterator<String> iterator = list.listIterator();

while(iterator.hasNext()){
   String item = iterator.next();
   
   // Change item value
   if(item.equals("1") iterator.set("4");
  
   // remove item
   if(item.equals("2") iterator.remove();
}

Please be noted, I haven't test the code yet.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah, I can replace the value throw this but I can't remove some of them without using iterator.
Thanks a lot, the updated code works. @ישו אוהב אותך
0

You need to be careful to avoid a ConcurrentModificationException when attempting to remove an element from a list while iterating over it. You can use this:

list = list.stream()
        .filter(element -> element != 1)
        .map(element -> 4)
        .collect(Collectors.toList());

3 Comments

Actually, the result of this answer is a list of boolean, it doesn't work.
The map should be replaced with map(element -> 4)
Yeah, typo. Sorry about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.