iterator for replacing list members in Java?

后端 未结 3 1889
囚心锁ツ
囚心锁ツ 2021-01-07 16:34

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

Is there an efficient way to

相关标签:
3条回答
  • 2021-01-07 16:47

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

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

    0 讨论(0)
  • 2021-01-07 16:51

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

    0 讨论(0)
  • 2021-01-07 16:54

    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.

    0 讨论(0)
提交回复
热议问题