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?

Jon Skeet
people
quotationmark

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();
    }
}

people

See more on this question at Stackoverflow