java项目老弹出,如何从Java中的集合中弹出项目?

本文介绍了一种从Java.util.List中移除并返回指定元素集合的方法。提供了自定义的pop方法实现,并讨论了使用Deque和迭代器的替代方案。强调了了解实际需求的重要性。

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 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值