[英]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.