I am removing elements from a list in one loop and this list is being iterated in another loop. ConcurrentModificationException
was expected. Is there a work around to solve this?
The point is I already have a loop and based on certain conditions I have to reduce its size and after modification it should iterate according to new size of the list. The list modification is happening in another loop.
static List<String> list = new ArrayList<>();
private static void initilizeList() {
for(int i = 0; i < 10; i++){
list.add(String.valueOf(i));
}
}
private static void iterateList() {
for(String s: list){
System.out.println(s);
if(s.equals("5")){
modifyList();
}
}
}
private static void modifyList() {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String element = iterator.next();
if (element.equalsIgnoreCase("5")) {
break;
}
iterator.remove();
}
}