问题描述
我想知道是否有一个快速/干净的方法来得到两组之间的差异?
我有:
设置< String> s1 = new HashSet< String>();
s1.add(a);
s1.add(b);
s1.add(c);
设置< String> s2 = new HashSet< String>();
s2.add(b);
我需要像:
设置< String> diff = Something.diff(s1,s2);
// diff将包含[a,c]
只是为了澄清我需要对称的区别。
可以使用媒体库中的一些功能(这真的很棒,我强烈推荐!): / p>
Sets.difference(s1,s2);
Sets.symmetricDifference(s1,s2);
Javadocs 和
symmetricDifference()
完全,但 difference()
也常常有帮助。
两个方法都返回一个实时视图,但是你可以在结果集上调用 .immutableCopy()
来获得一个不变的集合。如果你不想要一个视图,但需要一个set实例,你可以修改,调用 .copyInto(s3)
。有关这些方法,请参见。 p>
I'm wondering if there is a quick/clean way to get the difference between two sets ?
I have:
Set<String> s1 = new HashSet<String>();
s1.add("a");
s1.add("b");
s1.add("c");
Set<String> s2 = new HashSet<String>();
s2.add("b");
I need something like:
Set<String> diff = Something.diff(s1, s2);
// diff would contain ["a", "c"]
Just to clarify I need the symmetric difference.
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);
Javadocs for difference() and symmetricDifference()
symmetricDifference()
does exactly what you are asking for, but difference()
is also often helpful.
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中两个集合之间的对称差异是什么最好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!