[ACCEPTED]-iterator for replacing list members in Java?-iterator

Accepted answer
Score: 64

ListIterator.set as returned by List.listIterator() or List.listIterator(int)

(set wouldn't make any 1 sense for, say, a Set iterator.)

Score: 32

You need a ListIterator instead of an Iterator (listIterator() gives you one). Then 1 use the set method.

Score: 0

There is also List.replaceAll(UnaryOperator<E> operator) since Java 8.

This may be 12 more or less efficient than using a ListIterator (which 11 the default implementation does) depending 10 on the type of list that you are using and 9 how many elements you need to replace since 8 it can be overridden to provide better performance 7 but you can't short circuit it and quit 6 part way through (unless you throw an exception).

Some 5 lists (like CopyOnWriteArrayList) don't support modification 4 with a ListIterator but do support replaceAll.

Another advantage 3 is that replaceAll will probably be shorter to write 2 with a lambda than using a for loop with 1 an iterator.

More Related questions