如果我有两个集合:

Set<Integer> test1 = new HashSet<Integer>();
test1.add(1);
test1.add(2);
test1.add(3);

Set<Integer> test2 = new HashSet<Integer>();
test2.add(1);
test2.add(2);
test2.add(3);
test2.add(4);
test2.add(5);

是否有一种方法来比较它们,只返回一组4和5 ?


当前回答

Yes:

test2.removeAll(test1)

尽管这会使test2发生变异,所以如果需要保留它,请创建一个副本。

此外,您可能指的是<Integer>而不是<int>。

其他回答

Yes:

test2.removeAll(test1)

尽管这会使test2发生变异,所以如果需要保留它,请创建一个副本。

此外,您可能指的是<Integer>而不是<int>。

Java 8

我们可以使用removeIf,它接受一个谓词来编写一个实用方法:

// computes the difference without modifying the sets
public static <T> Set<T> differenceJava8(final Set<T> setOne, final Set<T> setTwo) {
     Set<T> result = new HashSet<T>(setOne);
     result.removeIf(setTwo::contains);
     return result;
}

如果我们仍然在以前的版本,那么我们可以使用removeAll as:

public static <T> Set<T> difference(final Set<T> setOne, final Set<T> setTwo) {
     Set<T> result = new HashSet<T>(setOne);
     result.removeAll(setTwo);
     return result;
}

添加一个解决方案,我最近用过,没有看到这里提到。如果你有Apache Commons Collections可用,那么你可以使用SetUtils#difference方法:

// Returns all the elements of test2 which are not in test1
SetUtils.difference(test2, test1) 

注意,根据文档,返回的集合是一个不可修改的视图:

返回一个不可修改的视图,其中包含给定集合的差值,用a \ b(或a - b)表示。 返回的视图包含a中不属于b的所有元素。

完整文档:https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/SetUtils.html#difference-java.util.Set-java.util.Set-

试试这个

test2.removeAll(test1);

组# removeAll

从此集合中删除指定集合中包含的所有元素(可选操作)。如果指定的集合也是一个集合,则此操作将有效地修改该集合,使其值为两个集合的非对称集之差。

顺序很重要,因为你需要4和5是int(不是Integer), 使用test2.removeAll (test1)。