[英]remove one Collection elements from other
Hi i have two Collection of SomeType a1,a2 and want to remove all the elements of a2 from a1. 嗨,我有两个SomeType a1,a2的集合,并想从a1中删除a2的所有元素。
Please suggestion which type of Collection i need to use : 请建议我需要使用哪种类型的馆藏:
Is there any library for this ? 有图书馆吗?
Thanks to all. 谢谢大家。 After reading your response i created a Filter class like this : 阅读您的回复后,我创建了一个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);
Well, you can use a1.removeAll(a2)
, but the removal would be more efficient if your Collections are HashSet
(since the search for an element in a HashSet takes O(1)
, while in List
s it takes O(n)
). 好吧,您可以使用a1.removeAll(a2)
,但是如果您的Collections是HashSet
,则删除会更有效(因为在HashSet
中搜索元素需要O(1)
,而在List
s中需要O(n)
)。 Whether you can use HashSet
depends on whether a1 and a2 can contain duplicate elements. 是否可以使用HashSet
取决于a1和a2是否可以包含重复元素。
To remove from a collection you need to have objects(in your case SomeType) that override equals
and hashCode
. 要从集合中删除,您需要具有覆盖equals
和hashCode
对象(在您的情况下为SomeType)。 Then you don't need a library, just use the removeAll
method 然后,您不需要库,只需使用removeAll
方法
Collection<SomeType> a1 = new ArrayList<SomeType>();
Collection<SomeType> a2 = new ArrayList<SomeType>();
a1.removeAll(a2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.