简体   繁体   English

从其他集合中删除一个集合元素

[英]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 : 请建议我需要使用哪种类型的馆藏:

  1. ArrayList 数组列表
  2. LinkList 链表
  3. some other ?. 其他 ?。

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 . 要从集合中删除,您需要具有覆盖equalshashCode对象(在您的情况下为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.

相关问题 Java集合:将集合中的元素相互比较,并在一个周期内删除 - Java collections: Compare elements in collection with each other and remove in one cycle 从集合中删除元素 - Remove elements from collection 是否存在一种更优雅的方法来将元素从一个集合中抽取到另一个集合中? - Is there a more elegant approach toward draining elements from one collection to the other? 如何在迭代Collection时安全地从Collection中删除其他元素 - How to safely remove other elements from a Collection while iterating through the Collection 使用迭代器从 Java 集合中删除元素 - Using Iterators to remove elements from a Java Collection 迭代时从集合中删除元素 - Remove elements from collection while iterating Java:从列表中删除以其他列表中的元素开头的元素 - Java : remove from list elements that start with elements from other list 如何在不使用迭代器进行迭代的同时从集合中删除元素 - How to remove elements from collection while iterating without iterator 对一个集合的元素执行操作,并对结果进行迭代以执行其他操作 - Performing an operation over the elements of one collection and iterating over the result to perform some other operation 如何在Java中将元素从一个JList传输到另一JList? - How to transfer the elements from one JList to other JList in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM