remove elements from CopyOnWriteArrayList

前端 未结 9 2003
醉酒成梦
醉酒成梦 2020-12-29 09:27

I am getting an exception when I try to remove elements from CopyOnWriteArrayList using an iterator. I have noticed that it is documented

Element-c

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 10:21

    the shortest and most efficient way:

    List list = new CopyOnWriteArrayList<>();
    list.removeIf(s -> s.length() < 1);
    

    internally it creates an temporary array with the same length and copies all elements where the predicate returns true.

    keep in mind that if you use this method to actually iterate over the elements to perform some action, these actions cannot be performed in paralell anymore since the removeIf-call is atomic and will lock the traversal for other threads

提交回复
热议问题