[java] In Java, can you modify a List while iterating through it?

I understand that in Java a Collection<E> should not be modified while iterating through it, such as removing or adding elements. But what about changing the elements in a List? For example, what if we have

List<String> letters = new ArrayList<String>();
letters.add("A");
letters.add("B");
letters.add("C");
int i = 0;

for (String letter : letters) {
    letters.set(i, "D");
    i++;
}

So, I'm not talking about modifying the object stored at an element; I'm talking about changing what the object is. The size of the List is not being changed, but the object at the index is changing, so technically the List is being modified. My boss claims this code is fine (and it does appear to work), but I still don't think it is correct. Would a different way of doing it, maybe using the set(E e) method of a ListIterator, be better?

This question is related to java arraylist

The answer is


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();
    }
}

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));