簡體   English   中英

Java中兩組的對稱差異

[英]Symmetric difference of two sets in Java

我的應用程序中有兩個TreeSet

set1 = {501,502,503,504}
set2 = {502,503,504,505}

我想獲得這些集的對稱差異 ,以便我的輸出將是集合:

set = {501,505}

你是在對稱差異之后 這在Java教程中討論。

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

您可以使用CollectionUtils#disjunction

編輯:

或者使用較少的Java-5之前的版本,使用Guava Sets#symmetricDifference

那些尋找set減法/補語 (非對稱差異/分離)的人可以使用CollectionUtils.subtract(a,b)Sets.difference(a,b)

使用保留所有,刪除所有然后addAll來做現有集合的聯合。

  1. intersectionSet.retainAll(set2)// intersectionSet是set1的副本
  2. set1.addAll(SET2); //做一個set1和set2的聯合
  3. 然后刪除重復項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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM