Jason S
Jason S

Reputation: 189726

iterator for replacing list members in Java?

Hmmm... the Java Iterator<T> has a remove() method but not a replace(T replacement) method.

Is there an efficient way to replace selected items in a List? I can use a for-loop to call get(i) and set(i) which is fine for ArrayList, but would suck for a linked list.

Upvotes: 40

Views: 22819

Answers (3)

Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15507

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.

Upvotes: 0

Michael Myers
Michael Myers

Reputation: 191965

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

Upvotes: 35

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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

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

Upvotes: 65

Related Questions