java sample code to calculate the difference in symmetry between sets

  • 2020-09-28 08:54:15
  • OfStack

sequence

This paper briefly introduces several methods for calculating set symmetry difference.

maven


    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>22.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.1</version>
    </dependency>

Symmetric difference

The difference in symmetry between two sets is a set of elements that belong to only one set but not the other.

Set A and B symmetric difference is usually expressed as A Δ B, symmetric difference symbols in some graph theory books � also use symbols to represent. For example: the symmetry difference between sets {1,2,3} and {3,4} is {1,2,4}.

guava

In guava we use the symmetricDifference method


    Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 3, 4));
    Set<Integer> b = new HashSet<>(Arrays.asList(3, 4, 5, 6));
    Sets.SetView<Integer> result = Sets.symmetricDifference(a,b);
    System.out.println(result);

collection4

In collection4 we use the disjunction method


    Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
    Set<Integer> b = new HashSet<>(Arrays.asList(1, 2, 3));
    SetUtils.SetView<Integer> result = SetUtils.disjunction(a, b);
    assertTrue(result.toSet().contains(5) && result.toSet().contains(3));

To improve the

The above two methods cannot mark which elements belong to the first set and which belong to the second set. Sometimes when we want to get the difference of symmetry, we can calculate which element belongs to which set. In this case, we can imitate the method in collection4 to get:


public static <O> Pair<Collection<O>,Collection<O>> disjunction2(final Collection<? extends O> first,
                                  final Collection<? extends O> second,
                                  final Predicate<O> p) {
    final List<O> firstList = first.stream()
        .filter(e -> p.evaluate(e))
        .collect(Collectors.toList());

    final List<O> secondList = second.stream()
        .filter(e -> !firstList.remove(e))
        .collect(Collectors.toList());
    return Pair.of(firstList,secondList);
  }

The instance


final List<String> first = Arrays.asList("bbb", "ccc","dddd","aaa");
final List<String> second = Arrays.asList("aaa", "zzz", "ccc");
System.out.println(disjunction(first,second,TruePredicate.truePredicate()));

The output

([bbb, dddd],[zzz])


Related articles: