Java Utility Library

Java Collections - disjoint() Method



The java.util.Collections.disjoint() method returns true if the two specified collections have no elements in common.

Syntax

public static boolean disjoint(Collection<?> c1, 
                               Collection<?> c2)

Here, T is the type of element in the list.


Parameters

c1 Specify a collection.
c2 Specify another collection.

Return Value

Returns true if the two specified collections have no elements in common.

Exception

  • Throws NullPointerException, if either collection is null.
  • Throws NullPointerException, if one collection contains a null element and null is not an eligible element for the other collection. (optional)
  • Throws ClassCastException, if one collection contains an element that is of a type which is ineligible for the other collection. (optional)

Example:

In the example below, the java.util.Collections.disjoint() method is used to check whether given collections are disjoint or not.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list objects
    List<Integer> list1 = new ArrayList<Integer>();
    List<Integer> list2 = new ArrayList<Integer>();
    List<Integer> list3 = new ArrayList<Integer>();

    //populating list1
    list1.add(10);
    list1.add(20);

    //populating list2
    list2.add(20);
    list2.add(10);

    //populating list3
    list3.add(100);

    //checking list1 and list2 for disjoint
    boolean retval = Collections.disjoint(list1, list2);
    System.out.println("list1 and list2 are disjoint? - " + retval); 
    
    //checking list1 and list3 for disjoint
    retval = Collections.disjoint(list1, list3);
    System.out.println("list1 and list3 are disjoint? - " + retval);  
  }
}

The output of the above code will be:

list1 and list2 are disjoint? - false
list1 and list3 are disjoint? - true

❮ Java.util - Collections