In Java, can you modify a List while iterating through it?
Java 8's stream()
interface provides a great way to update a list in place.
To safely update items in the list, use map()
:
List<String> letters = new ArrayList<>();
// add stuff to list
letters = letters.stream().map(x -> "D").collect(Collectors.toList());
To safely remove items in place, use filter()
:
letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());
Use CopyOnWriteArrayList
and if you want to remove it, do the following:
for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
{
if (wordsToRemove.contains(word))
{
it.remove();
}
}
There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:
for (int i = 0; i < letters.size(); i++) {
letters.set(i, "D");
}
At the end the whole list will have the letter "D"
as its content. It's not a good idea to use an enhanced for
loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.
Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:
A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification