Java Utililty Methods Set Difference

List of utility methods to do Set Difference

Description

The list of methods to do Set Difference are organized into topic(s).

Method

SetcomputeDifference(Set a, Set b, String prefix, boolean exactMatch)
compute Difference
Set<String> overlap = new HashSet<String>();
for (Iterator<String> it = a.iterator(); it.hasNext();) {
    String code = it.next();
    if (!exactMatch && code.startsWith(prefix))
        if (!b.contains(code))
            overlap.add(code);
    if (exactMatch)
        if (!b.contains(code))
...
SetdiffAbyB(Set setA, Set setB)
A = {1, 2, 3, 4, 5} and B = {3, 4, 5, 6, 7, 8}.
if (isEmpty(setA) && !isEmpty(setB)) {
    return Collections.unmodifiableSet(setB);
if (!isEmpty(setA) && isEmpty(setB)) {
    return Collections.unmodifiableSet(setA);
if (isEmpty(setA) && isEmpty(setB)) {
    return Collections.unmodifiableSet(new LinkedHashSet<T>());
...
Setdifference(final Set set1, final Set set2)
difference
Set<E> set = new HashSet<>(set1);
set.removeAll(set2);
return Collections.unmodifiableSet(set);
Setdifference(final Set first, final Set second)

Returns a set containing all the elements which are not contained by the two given sets.

final Set<T> retval = new HashSet<T>();
for (final T e : first) {
    if (!second.contains(e)) {
        retval.add(e);
for (final T e : second) {
    if (!first.contains(e)) {
...
Setdifference(Set a, Set b)
difference
Set temp = new HashSet();
temp.addAll(a);
temp.removeAll(b);
return temp;
Setdifference(Set first, Set second)
difference
Set<T> copyOfFirst = new LinkedHashSet<>(first);
copyOfFirst.removeAll(second);
return copyOfFirst;
Setdifference(Set s1, Set s2)
Return is s1 \ s2
Set<T> s3 = new HashSet<T>(s1);
s3.removeAll(s2);
return s3;
Setdifference(Set setA, Set setB)
This method finds the difference between set A and set B i.e.
Set<T> difference = new HashSet<T>(setA);
difference.removeAll(setB);
return difference;