iterator for replacing list members in Java?

后端 未结 3 1888
囚心锁ツ
囚心锁ツ 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:54

    There is also List.replaceAll(UnaryOperator 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.

提交回复
热议问题