Redian新闻
>
Simple question: delete element from collection on condition?
avatar
Simple question: delete element from collection on condition?# Java - 爪哇娇娃
g*y
1
I find this annoyance in ArrayList/HashSet/HashMap...
If I want to loop through iterator and delete some elements on condition, I
have to do it:
1. Loop through iterator and find all elements satisfy condition, save them
in a collection.
2. Delete temp collection elements from original collection.
I have to do two steps because iterator can't be broken during loop. Is
there a better/simpler way to do this? I have no limitation on the data
structure.
Thanks.
avatar
g*g
2
This is probably the best practice anyway, you know
delete one item at a time from an Array can be N times
slower than what you are doing here.

I
them

【在 g**********y 的大作中提到】
: I find this annoyance in ArrayList/HashSet/HashMap...
: If I want to loop through iterator and delete some elements on condition, I
: have to do it:
: 1. Loop through iterator and find all elements satisfy condition, save them
: in a collection.
: 2. Delete temp collection elements from original collection.
: I have to do two steps because iterator can't be broken during loop. Is
: there a better/simpler way to do this? I have no limitation on the data
: structure.
: Thanks.

avatar
m*t
3
You can certainly do iterator.remove() while in the loop. That's what
AbstractCollection.removeAll does anyway.

I
them

【在 g**********y 的大作中提到】
: I find this annoyance in ArrayList/HashSet/HashMap...
: If I want to loop through iterator and delete some elements on condition, I
: have to do it:
: 1. Loop through iterator and find all elements satisfy condition, save them
: in a collection.
: 2. Delete temp collection elements from original collection.
: I have to do two steps because iterator can't be broken during loop. Is
: there a better/simpler way to do this? I have no limitation on the data
: structure.
: Thanks.

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。