Is there a method in JDK or apache commons to “pop” a list of elements from a java.util.List? I mean, remove the list of elements and return it, like this method:
public Collection pop(Collection elementsToPop, Collection elements) {
Collection popped = new ArrayList();
for (Object object : elementsToPop) {
if (elements.contains(object)) {
elements.remove(object);
popped.add(object);
}
}
return popped;
}
If you’re looking for a stack-like structure I suggest accepting a
Deque(LinkedListis the most common implementation) instead of aCollection.If you don’t actually need to treat it as a stack, just get an iterator from the
Collectionand use theremove()method:Do note that remove is an optional operation, and some implementations may throw an
UnsupportedOperationException(for example, the iterator returned by a Collection fromCollections.unmodifiable...()will).Edit: After looking more closely at your question, I think you just need this:
If your main point is you need to know exactly which elements were actually popped, I think you’re stuck with your original code.