从另一个中删除一个 Collection 元素

remove one Collection elements from other

你好,我有两个 SomeType a1,a2 的集合,我想从 a1 中删除 a2 的所有元素。

请建议我需要使用哪种类型的集合:

  1. 数组列表
  2. 链表
  3. 其他一些 ?.

有这方面的库吗?

使用采集方式Collection.removeAll(Collection<?> c);

好吧,您可以使用 a1.removeAll(a2),但如果您的集合是 HashSet,删除会更有效(因为在 HashSet 中搜索元素需要 O(1),而在 List 秒内需要 O(n))。能不能用HashSet取决于a1和a2是否可以包含重复元素。

要从集合中删除,您需要具有覆盖 equalshashCode 的对象(在您的情况下为 SomeType)。 那你就不用库了,直接用removeAll方法

Collection<SomeType> a1 = new ArrayList<SomeType>();
Collection<SomeType> a2 = new ArrayList<SomeType>();
a1.removeAll(a2);

感谢大家。 阅读您的回复后,我创建了一个 Filter class,如下所示:

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;
    }
}