When I run this, I get a java.util.ConcurrentModificationException
despite me using iterator.remove();
it's obviously me adding the number 6 in the loop. Does this happen because the iterator "doesn't know" it's there and is there anyway to fix it?
public static void main(String args[]){
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
for(Iterator<String> it = list.iterator();it.hasNext();){
String value = it.next();
if(value.equals("4")) {
it.remove();
list.add("6");
}
System.out.println("List Value:"+value);
}
}
The ConcurrentModificationException
is thrown when calling String value = it.next();
. But the actual culprit is list.add("6");
. You mustn't modify a Collection
while iterating over it directly. You are using it.remove();
which is fine, but not list.add("6");
.
While you can solve the problem with Stream
s, I will first offer a solution with Iterator
s, as this is a good first step for understanding the problem.
You need a ListIterator<String>
if you want to add and remove during iteration:
for (ListIterator<String> it = list.listIterator(); it.hasNext();){
String value = it.next();
if (value.equals("4")) {
it.remove();
it.add("6");
}
System.out.println("List Value: " + value);
}
This should do the trick!
A solution using Stream
s:
List<String> newList = list.stream()
.map(s -> s.equals("4") ? "6" : s)
.collect(Collectors.toList());
Here we create a Stream
from your List
. We map
all values to themselves, only "4"
gets mapped to "6"
and then we collect it back into a List
. But caution, newList
is immutable!
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