1

How do I remove uncommon elements from ArrayList? The scenario is I have two ArrayList objects: arr1 and arr2. arr2 contains almost all elements of arr1. Now I want to remove such elements from arr1, which are not in arr2.

How can i achieve this? Is there any method or any technique to remove uncommon elements between two ArrayList objects?

4

5 回答 5

4

用途CollectionUtils.retainAll:返回一个集合,其中包含 collection1 中的所有元素,这些元素也在 collection2 中。

ArrayList commonList = CollectionUtils.retainAll(list1,list2);

然后用 for 循环删除不常见的元素

于 2013-01-15T07:09:42.900 回答
3

您可以使用retainAllArrayList 中实现的方法。它就像一个固定的交叉点。

于 2013-01-15T07:08:34.967 回答
1

怎么样arr1.retainAll(arr2);

于 2013-01-15T07:14:18.530 回答
1

方法一:

arr1.retainAll(arr2)

方法二:

    List<String> arr1;
    List<String> arr2 ;

    for(String s: arr2){
        if(arr1.contains(s))
            arr1.remove(s);
    }

我个人认为 1 表现力和性能效率更高。如果 arr1 不等于 arr2,JDK 使用System.arraycopy()完整复制arr2arr1而不是删除单个元素。System.arraycopy 是原生实现的,速度非常快。

以下是执行此操作的 JDK 代码的参考。

    private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

如果只有很少的元素会有所不同,那么方法 2 会更好。

于 2013-01-15T07:31:25.463 回答
0

这是我基于以前的一些答案的解决方案

/**
 * Returns elements in List A that are not in List B. (i.e. the relative complement of A with respect to B)
 * see https://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_complement
 * @param a
 * @param b
 * @return
 */
private <E> List<E> relativeComplement(List<E> a, List<E> b) {
    return ListUtils.removeAll(a, ListUtils.retainAll(a,b));
}
于 2017-08-16T14:58:01.407 回答