Hi i have two Collection of SomeType a1,a2 and want to remove all the elements of a2 from a1.
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 :
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)
). Whether you can use HashSet
depends on whether a1 and a2 can contain duplicate elements.
To remove from a collection you need to have objects(in your case SomeType) that override equals
and hashCode
. Then you don't need a library, just use the removeAll
method
Collection<SomeType> a1 = new ArrayList<SomeType>();
Collection<SomeType> a2 = new ArrayList<SomeType>();
a1.removeAll(a2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.