Symmetric difference of two sets in Java

2020-05-23 02:47发布

问题:

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 these sets so that my output would be the set:

set = {501,505}

回答1:

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


回答2:

You could use CollectionUtils#disjunction

EDIT:

Alternatively with less pre-Java-5-ness, use Guava Sets#symmetricDifference



回答3:

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


回答4:

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



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

output of s1 : [a,c]



回答6:

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.



回答7:

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]