简体   繁体   English

是否存在一种更优雅的方法来将元素从一个集合中抽取到另一个集合中?

[英]Is there a more elegant approach toward draining elements from one collection to the other?

Based on a condition, certain elements should be drained from one collection to the other. 根据条件,某些元素应从一个集合中流失到另一个集合中。 To avoid concurrent modification, my current approach is (pseudo code): 为了避免并发修改,我目前的方法是(伪代码):

Set<Integer> drained
for (i in sourceCollection index)
    if (condition met)
        drained.add(i)
        destinationCollection.add(element)

Collection<Object> remaining
for (i in sourceCollection index)
    if (i not in drained)
        remaining.add(element)

sourceCollection = remaining

Is there a shorter/elegant approach? 有没有一种简短/优雅的方法?

You can use an iterator for this: 您可以为此使用迭代器:

for (Iterator<String> iterator = source.iterator(); iterator.hasNext(); ) {
    String element = iterator.next();
    if (shouldDrain(element)) {
        destination.add(element);
        iterator.remove();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM