Symmetric difference of two sets in Java

前端 未结 7 2000
礼貌的吻别
礼貌的吻别 2021-02-03 21:49

There are two TreeSets in my app:

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

I want to get the symmetric difference of thes

相关标签:
7条回答
  • 2021-02-03 22:25

    Those looking for set subtraction/complement (not symmetric difference/disjunction) can use CollectionUtils.subtract(a,b) or Sets.difference(a,b).

    0 讨论(0)
  • 2021-02-03 22:31

    use retain all,remove all then addAll to do a union of existing set.

    1. intersectionSet.retainAll(set2) // intersectionSet is a copy of set1
    2. set1.addAll(set2); // do a union of set1 and set2
    3. then remove the duplicates set1.removeAll(intersectionSet);
    0 讨论(0)
  • 2021-02-03 22:34
    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);
    

    output of s1 : [a,c]

    0 讨论(0)
  • 2021-02-03 22:35

    You're after the symmetric difference. This is discussed in the Java tutorial.

    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
    
    0 讨论(0)
  • 2021-02-03 22:40

    if we use package com.google.common.collect, we may ellegantly find symmetric difference like this :

        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 ));
    

    The output will be : [1, 5]

    0 讨论(0)
  • 2021-02-03 22:49

    You could try Sets.symmetricDifference() from Eclipse Collections.

    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);
    

    Note: I am a committer for Eclipse Collections.

    0 讨论(0)
提交回复
热议问题