Looking for a standard Java method (or, UDF if necessary) to check if one hashset is a subset of another

It should return true if one HashSet A is a subset of another HashSet B, false otherwise.

Upvotes: 0

Views: 44

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533750

Not sure if it has to be a strict subset or it can be equal.

Set a = ...
Set b = ...

If you can use containsAll

return b.containsAll(a);

or if it has to be a strict subset

return b.size() > a.size() && b.containsAll(a);

or you can

Set tmp = new HashSet(a);
tmp.removeAll(b);
return tmp.isEmpty();

Upvotes: 3

NPE
NPE

Reputation: 500773

Set.containsAll() does what you want:

Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set, this method returns true if it is a subset of this set.

Upvotes: 3

Sebastien
Sebastien

Reputation: 6542

Set.containsAll method should do the job:

B.containsAll(A)

Upvotes: 2

Related Questions