java - 获取两组之间的差异

标签 java set

所以如果我有两套:

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?

最佳答案

试试这个

test2.removeAll(test1);

Set#removeAll

Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.

关于java - 获取两组之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644579/

相关文章:

java - 在 iText 中使用 PdfGraphics2D 绘图时使用什么单位

java - 两个对象通过最终引用相互引用

java - 关于Java中数组的问题

java - 即使我们在不同的线程中使用不同的锁,为什么值设置正确

algorithm - 有没有一种方法可以生成一个单一的键来记住我们遇到的所有字符串

c++ - std::set 和 < 运算符重载的奇怪行为?

java - 在 Web 服务中包装存储过程的最简单方法是什么?

recursion - 什么是递归可枚举集?

python - 现场交叉口操作

c++ - 将数组转换为 C++ 中的集合