[ACCEPTED]-iterator for replacing list members in Java?-iterator
ListIterator.set
as returned by List.listIterator()
or List.listIterator(int)
(set
wouldn't make any 1 sense for, say, a Set
iterator.)
You need a ListIterator
instead of an Iterator
(listIterator()
gives you one). Then 1 use the set
method.
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.