如何从Java中的集合中弹出项目? [英] How to pop items from a collection in Java?
问题描述
在JDK或apache commons中有一个方法来弹出一个来自java.util.List的元素列表吗?我的意思是,删除元素列表并返回它,像这样的方法:
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;
}
一个堆栈式结构我建议接受 Deque
( LinkedList
是最常见的实现)而不是 Collection
。
如果你实际上不需要把它当作栈,只需从 Collection
并使用 remove()
方法:
for(Iterator< SomeType> it = elements.iterator(); it.hasNext();){
SomeType e = it.next();
it.remove();
popped.add(e);
}
请注意,remove是一个可选操作, code> UnsupportedOperationException (例如,从 Collections.unmodifiable ...()
的集合返回的迭代器将会)。
编辑:仔细查看您的问题后,我认为您只需要:
elements.removeAll(elementsToRemove);
如果你的要点是你需要准确知道 popped,我想你卡住你的原始代码。
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
(LinkedList
is the most common implementation) instead of a Collection
.
If you don't actually need to treat it as a stack, just get an iterator from the Collection
and use the remove()
method:
for (Iterator<SomeType> it = elements.iterator(); it.hasNext(); ) {
SomeType e = it.next();
it.remove();
popped.add(e);
}
Do note that remove is an optional operation, and some implementations may throw an UnsupportedOperationException
(for example, the iterator returned by a Collection from Collections.unmodifiable...()
will).
Edit: After looking more closely at your question, I think you just need this:
elements.removeAll(elementsToRemove);
If your main point is you need to know exactly which elements were actually popped, I think you're stuck with your original code.
这篇关于如何从Java中的集合中弹出项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!