在Java中查找两个ArrayLists之间的不同元素

zhr*_*ani 8 java arraylist

我如何知道java中2个数组列表之间的不同元素?我需要确切的元素而不是布尔值,可以使用它来检索removeAll().

anu*_*ava 10

如果我正确地理解了你的问题,那么下面nonOverLap的代码中的跟随方法应该会让你:

<T> Collection<T> union(Collection<T> coll1, Collection<T> coll2) {
    Set<T> union = new HashSet<>(coll1);
    union.addAll(new HashSet<>(coll2));
    return union;
}

<T> Collection<T> intersect(Collection<T> coll1, Collection<T> coll2) {
    Set<T> intersection = new HashSet<>(coll1);
    intersection.retainAll(new HashSet<>(coll2));
    return intersection;
}

<T> Collection<T> nonOverLap(Collection<T> coll1, Collection<T> coll2) {
    Collection<T> result = union(coll1, coll2);
    result.removeAll(intersect(coll1, coll2));
    return result;
}
Run Code Online (Sandbox Code Playgroud)


pal*_*int 10

使用Apache Commons Collections(javadoc):

CollectionUtils.disjunction(a, b);
Run Code Online (Sandbox Code Playgroud)

另请参阅:Effective Java,第2版,第47项:了解和使用库(作者仅提到了JDK的内置库,但我认为其他库的推理也是如此.)


Enr*_*que 1

LinkedHashMap table;
for each element e of array A
    if table.get(e) != null
        table.put( e, table.get(e) + 1 )
    else
       table.put( e, 0 )

//Do the same for array B
for each element e of array B
    if table.get(e) != null
        table.put( e, table.get(e) + 1 )
    else
       table.put( e, 0 )
Run Code Online (Sandbox Code Playgroud)

在 for 循环的末尾,表中 value=0 的元素是不同的。