What is the best way get the symmetric difference between two sets in java?(在java中获得两组之间对称差异的最佳方法是什么?)
问题描述
我想知道是否有一种快速/干净的方法来获得两组之间的对称差异?
I'm wondering if there is a quick/clean way to get the symmetric difference between two sets ?
我有:
Set<String> s1 = new HashSet<String>();
s1.add("a");
s1.add("b");
s1.add("c");
Set<String> s2 = new HashSet<String>();
s2.add("b");
我需要类似的东西:
Set<String> diff = Something.diff(s1, s2);
// diff would contain ["a", "c"]
<小时>
只是为了澄清我需要对称差异.
推荐答案
你可以使用 Google Guava 库(真的很棒,我强烈推荐它!):
You can use some functions from the Google Guava library (which is really great, I strongly recommend it!):
Sets.difference(s1, s2);
Sets.symmetricDifference(s1, s2);
difference() 和 symmetricDifference()
symmetricDifference() 完全符合 您的要求,但 difference() 通常也很有帮助.
symmetricDifference() does exactly what you are asking for, but difference() is also often helpful.
这两种方法都返回实时视图,但您可以例如在结果集上调用 .immutableCopy() 以获得不变集.如果您不想要视图,但需要一个可以修改的集合实例,请调用 .copyInto(s3).请参阅 SetView 对于这些方法.
Both methods return a live view, but you can for example call .immutableCopy() on the resulting set to get a non-changing set. If you don't want a view, but need a set instance you can modify, call .copyInto(s3). See SetView for these methods.
这篇关于在java中获得两组之间对称差异的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在java中获得两组之间对称差异的最佳方法是什么?
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
