[英]What is the best way get the symmetric difference between two sets in java?
[英]Symmetric difference of two sets in Java
我的應用程序中有兩個TreeSet
:
set1 = {501,502,503,504}
set2 = {502,503,504,505}
我想獲得這些集的對稱差異 ,以便我的輸出將是集合:
set = {501,505}
Set<Type> symmetricDiff = new HashSet<Type>(set1);
symmetricDiff.addAll(set2);
// symmetricDiff now contains the union
Set<Type> tmp = new HashSet<Type>(set1);
tmp.retainAll(set2);
// tmp now contains the intersection
symmetricDiff.removeAll(tmp);
// union minus intersection equals symmetric-difference
那些尋找set減法/補語 (非對稱差異/分離)的人可以使用CollectionUtils.subtract(a,b)
或Sets.difference(a,b)
。
使用保留所有,刪除所有然后addAll來做現有集合的聯合。
- intersectionSet.retainAll(set2)// intersectionSet是set1的副本
- set1.addAll(SET2); //做一個set1和set2的聯合
- 然后刪除重復項set1.removeAll(intersectionSet);
您可以嘗試從Eclipse Collections中設置 Sets.symmetricDifference()
。
Set<Integer> set1 = new TreeSet<>(Arrays.asList(501,502,503,504));
Set<Integer> set2 = new TreeSet<>(Arrays.asList(502,503,504,505));
Set<Integer> symmetricDifference =
Sets.symmetricDifference(set1, set2);
Assert.assertEquals(
new TreeSet<>(Arrays.asList(501, 505)),
symmetricDifference);
注意:我是Eclipse Collections的提交者。
如果我們使用com.google.common.collect包,我們可能會發現這樣的對稱差異:
Set<Integer> s1 = Stream.of( 1,2,3,4,5 ).collect( Collectors.toSet());
Set<Integer> s2 = Stream.of( 2,3,4 ).collect( Collectors.toSet());
System.err.println(Sets.symmetricDifference( s1,s2 ));
輸出將是:[1,5]
Set<String> s1 = new HashSet<String>();
Set<String> s2 = new HashSet<String>();
s1.add("a");
s1.add("b");
s2.add("b");
s2.add("c");
Set<String> s3 = new HashSet<String>(s1);
s1.removeAll(s2);
s2.removeAll(s3);
s1.addAll(s2);
System.out.println(s1);
輸出s1:[a,c]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.