Disjoint Collection Method in Apex?

It doesn't appear to be provided as a method, but you can easily do that using the tools Salesforce does provide us.

Set<Integer> set1 = new Set<Integer>{1, 2, 3};
Set<Integer> set2 = new Set<Integer>{1, 2};
Set<Integer> set3 = new Set<Integer>{4, 5, 6};

set1.retainAll(set2);         // Should result in {1, 2}
System.debug(set1.isEmpty()); // False, not disjoint, because both sets contained {1, 2}

set1.retainAll(set3);         // Should result in an empty set
System.debug(set1.isEmpty()); // True, is disjoint

No, but you can hack it out of methods that do exist.

Given set1 and set2:

Set<T> tempSet = set1.clone();
tempSet.retainAll(set2);
Boolean containsAny = tempSet.isEmpty();

Create a temporary copy of set1, retain only items in set2, and it's either empty or not.

EDIT: Thanks for Derek F's correction.

Tags:

Apex