如何从Java中的集合中弹出项目? [英] How to pop items from a collection in Java?

查看:273
本文介绍了如何从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆