Getting the difference between two sets(获取两组之间的差异)
问题描述
所以如果我有两套:
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?
Is there a way to compare them and only have a set of 4 and 5 returned?
推荐答案
试试这个
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 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01