Hmmm... the Java Iterator
has a remove()
method but not a replace(T replacement)
method.
Is there an efficient way to
ListIterator.set as returned by List.listIterator() or List.listIterator(int)
(set
wouldn't make any sense for, say, a Set
iterator.)
You need a ListIterator instead of an Iterator
(listIterator() gives you one). Then use the set method.
There is also List.replaceAll(UnaryOperator<E> operator) since Java 8.
This may be more or less efficient than using a ListIterator
(which the default implementation does) depending on the type of list that you are using and how many elements you need to replace since it can be overridden to provide better performance but you can't short circuit it and quit part way through (unless you throw an exception).
Some lists (like CopyOnWriteArrayList
) don't support modification with a ListIterator
but do support replaceAll
.
Another advantage is that replaceAll
will probably be shorter to write with a lambda than using a for loop with an iterator.