![](/img/trans.png)
[英]Java collections: Compare elements in collection with each other and remove in one cycle
[英]remove one Collection elements from other
嗨,我有两个SomeType a1,a2的集合,并想从a1中删除a2的所有元素。
请建议我需要使用哪种类型的馆藏:
有图书馆吗?
谢谢大家。 阅读您的回复后,我创建了一个Filter类,如下所示:
public class Filter {
public <T> Set<T> filter(Set<T> all, Set<T> blocked) {
for (T t : all) {
if(blocked.contains(t)) {
all.remove(t);
}
}
return all;
}
}
使用收集方法Collection.removeAll(Collection<?> c);
好吧,您可以使用a1.removeAll(a2)
,但是如果您的Collections是HashSet
,则删除会更有效(因为在HashSet
中搜索元素需要O(1)
,而在List
s中需要O(n)
)。 是否可以使用HashSet
取决于a1和a2是否可以包含重复元素。
要从集合中删除,您需要具有覆盖equals
和hashCode
对象(在您的情况下为SomeType)。 然后,您不需要库,只需使用removeAll
方法
Collection<SomeType> a1 = new ArrayList<SomeType>();
Collection<SomeType> a2 = new ArrayList<SomeType>();
a1.removeAll(a2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.