No, it's not safe, and can throw ConcurrentModificationException
. You can collect all the elements to be removed in a temporary List
, and then call list.removeAll(tmpList)
after the while loop to perform the removal.
Iterator<String> iterator = nameList.iterator();
List<String> removed = new ArrayList<>();
while(iterator.hasNext()){
String s = iterator.next();
removed.addAll(work(s));
}
list.removeAll(removed);
I realize this can be less efficient, since you might be calling work(s)
on String
s the should have been removed from the List
earlier. This can be improved by changing tempList
to a Set
, and only calling work(s)
for String
s not in the Set
:
Iterator<String> iterator = nameList.iterator();
Set<String> removed = new HashSet<>();
while(iterator.hasNext()){
String s = iterator.next();
if (!removed.contains(s)) {
removed.addAll(work(s));
}
}
list.removeAll(removed);