Does the disjoint method (mentioned in the Java documentation here exist in Apex? To summarize the method takes two Lists/Sets and compares them to see if either contains an element in the other and returns true if they do.

2 Answers 2


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
  • Good work around and cleaner than what i came up with but wish it didn't mutate the original set (though as Charles did below, cloning is certainly an option)
    – Bobbygllh
    Dec 6, 2019 at 19:05

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

Given set1 and set2:

Set<T> tempSet = set1.clone();
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.

  • 1
    Close, but we can't chain those particular methods. retainAll() and removeAll() return Boolean instead of a set.
    – Derek F
    Dec 5, 2019 at 22:24
  • oops, fair point!
    – Charles T
    Dec 6, 2019 at 0:33
  • (It's kind of awful that the available methods all mutate the Set rather than return a new one)
    – Charles T
    Dec 6, 2019 at 0:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.