简体   繁体   中英

Symmetric difference of two sets in Java

There are two TreeSet s 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}

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

You could use CollectionUtils#disjunction

EDIT:

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

那些寻找set减法/补语 (非对称差异/分离)的人可以使用CollectionUtils.subtract(a,b)Sets.difference(a,b)

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

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.

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]

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM