No, this is not safe, and may throw a ConcurrentModificationException . You can collect all the items that you want to remove in the temporary List , and then call list.removeAll(tmpList) after the while loop to perform the deletion.
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 understand that this may be less efficient, since you could call work(s) on a String , it should have been removed from the List earlier. This can be improved by changing tempList to Set and calling only work(s) for String not in 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);
source share