Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Set B has at least one element that is not in Set A

Tags:

java

java-8

set

So I have two sets: A and B. I need to check if set B contains anything that is not in the set A. There are maybe intersections, so I cannot just check if set A contains set B. I can obviously do this:

for (String string : setA) {
  if (!setB.contains(string) {
    break;
  }
}

or using the Guava library:

Sets.intersection(setA, setB).containsAll(setB); // returns false if there are elements outside.

But is there any way that would perform better or may be just cleaner or more elegant? Thanks.

like image 267
Battle_Slug Avatar asked Feb 02 '26 12:02

Battle_Slug


2 Answers

B contains an element not in A” is the exact opposite of “A contains all elements of B”, therefore, the already existing method containsAll is sufficient to answer that question.

if(!setA.containsAll(setB)) {
    System.out.println("setB contains an element not in setA");
}

You may shortcut using setB.size()>setA.size() || !setA.containsAll(setB), but this requires that the sets agree on the definition of equality, e.g. if one set is a SortedSet using String.CASE_INSENSITIVE_ORDER as comparator and the other is a HashSet, this won’t work (but the definition of the correct outcome is tricky with such combinations anyway).

If setB is really large, you might get a benefit from using a parallel stream like

if(!setB.parallelStream().allMatch(setA::contains)) {
    System.out.println("setB contains an element not in setA");
}

but this is rather rare.

like image 122
Holger Avatar answered Feb 04 '26 00:02

Holger


Merge all elements into another set and compare the total elements:

Set ab = new Set(a);
ab.addAll(b);

if (ab.size() != b.size()) break; // that means `a` had some element that was not in b
like image 33
Naman Avatar answered Feb 04 '26 01:02

Naman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!