Using Java’s Disjoint Method to Compare Lists

Published
Updated

You may encounter a situation where you need to check an Array, List, or Set’s elements for commonality. Here are a few different situations in which you can use Java’s Disjoint function:

  • Given two arrays, do any of the elements match between them?
  • Given two Lists, Sets, or Collections, are any of the elements the same?
  • Given two arrays, check that neither contain the same elements?
  • Given two collections, count how many of the elements are the same between them?

Java’s Disjoint Function Example

Under the java.util.Collections class is a function called disjoint();. This method tests two collections and will return true if neither List, Set, or Collection share any common elements.

List<Integer> listA = Arrays.asList({"Apple", "Orange", "Kiwi"});
List<Integer> listB = Arrays.asList({"Pineapple", "Banana", "Blueberry"});

boolean noMatch = Collections.disjoint(listA, listB);

// Prints True
System.out.println(noMatch);

This also can be used in reverse, if you invert the logic, you can determine if the two collections have any overlap, meaning (any) of the elements between the two are the same.

List<Integer> listA = Arrays.asList({"Apple", "Orange", "Kiwi"});
List<Integer> listB = Arrays.asList({"Pineapple", "Banana", "Apple"});

boolean overlap = !Collections.disjoint(listA, listB);

// Prints True
System.out.println(overlap);

This can be really useful in situations where you want to determine if any of the elements match the others. For example, checking a list of entitlements of a user against a list of authorized entitlements for a specific resource.