ZetCode

Java Collections.disjoint Method

Last modified: April 20, 2025

The Collections.disjoint method is a utility method in Java's Collections Framework. It checks whether two specified collections have no elements in common. This method is useful for determining if collections are mutually exclusive.

The method returns true if the collections have no common elements. It returns false if they share at least one element. The method is optimized for performance with different collection types.

Collections.disjoint Method Overview

The disjoint method is a static method in the java.util.Collections class. It takes two collections as parameters and returns a boolean value. The method signature is: public static boolean disjoint(Collection<?> c1, Collection<?> c2).

The method works with any Collection implementation. It handles null values properly and is thread-safe for concurrent access. The time complexity depends on the collection types provided.

Basic disjoint Example with Lists

This example demonstrates the basic usage of Collections.disjoint with two ArrayLists. We create two lists of strings and check if they have any elements in common.

DisjointBasicExample.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DisjointBasicExample {

    public static void main(String[] args) {
        
        List<String> list1 = new ArrayList<>();
        list1.add("Apple");
        list1.add("Banana");
        list1.add("Cherry");
        
        List<String> list2 = new ArrayList<>();
        list2.add("Orange");
        list2.add("Lemon");
        list2.add("Lime");
        
        boolean areDisjoint = Collections.disjoint(list1, list2);
        System.out.println("Are lists disjoint? " + areDisjoint);
        
        list2.add("Apple");
        areDisjoint = Collections.disjoint(list1, list2);
        System.out.println("After adding Apple: " + areDisjoint);
    }
}

In this example, we first check two lists with no common elements. The method returns true. Then we add "Apple" to the second list and check again. Now the method returns false because both lists contain "Apple".

The output shows how the method correctly identifies when collections share elements. This is useful for validation or conditional logic based on collection contents.

disjoint with Sets

This example shows how Collections.disjoint works with Set implementations. Sets are unordered collections that don't allow duplicates. We'll use HashSet and TreeSet in this demonstration.

DisjointWithSets.java
package com.zetcode;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class DisjointWithSets {

    public static void main(String[] args) {
        
        Set<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(3);
        
        Set<Integer> set2 = new TreeSet<>();
        set2.add(4);
        set2.add(5);
        set2.add(6);
        
        System.out.println("Disjoint initially: " + 
            Collections.disjoint(set1, set2));
            
        set2.add(3);
        System.out.println("After adding 3: " + 
            Collections.disjoint(set1, set2));
    }
}

This example demonstrates disjoint with different Set implementations. Initially, the sets have no common elements, so the method returns true. After adding element 3 to the second set, which already exists in the first set, the method returns false.

The example shows that disjoint works consistently across different Collection implementations. The method doesn't depend on the collection's ordering or implementation details.

disjoint with Mixed Collection Types

The Collections.disjoint method can work with different collection types simultaneously. This example demonstrates checking disjointness between a List and a Set.

DisjointMixedTypes.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DisjointMixedTypes {

    public static void main(String[] args) {
        
        List<String> list = new ArrayList<>();
        list.add("Red");
        list.add("Green");
        list.add("Blue");
        
        Set<String> set = new HashSet<>();
        set.add("Cyan");
        set.add("Magenta");
        set.add("Yellow");
        
        System.out.println("Disjoint initially: " + 
            Collections.disjoint(list, set));
            
        set.add("Green");
        System.out.println("After adding Green: " + 
            Collections.disjoint(list, set));
    }
}

This example shows that Collections.disjoint works seamlessly between different collection types. We first check a List and Set with no common elements, which returns true. After adding "Green" to the Set, which exists in the List, the method returns false.

The method's ability to work across different collection types makes it versatile. You can use it to compare any combination of Lists, Sets, Queues, etc., without worrying about their specific implementations.

disjoint with Empty Collections

This example explores how Collections.disjoint behaves with empty collections. We'll test various combinations of empty and non-empty collections to understand the edge cases.

DisjointEmptyCollections.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DisjointEmptyCollections {

    public static void main(String[] args) {
        
        List<String> emptyList1 = new ArrayList<>();
        List<String> emptyList2 = new ArrayList<>();
        List<String> nonEmptyList = new ArrayList<>();
        nonEmptyList.add("Item");
        
        System.out.println("Two empty lists: " + 
            Collections.disjoint(emptyList1, emptyList2));
            
        System.out.println("Empty and non-empty: " + 
            Collections.disjoint(emptyList1, nonEmptyList));
            
        System.out.println("Non-empty and empty: " + 
            Collections.disjoint(nonEmptyList, emptyList1));
    }
}

When both collections are empty, disjoint returns true because they share no elements. When comparing an empty collection with a non-empty one, it also returns true for the same reason.

These results demonstrate the method's logical consistency. Empty collections are always disjoint with any other collection, including other empty collections.

disjoint with Null Values

This example examines how Collections.disjoint handles null values in collections. We'll test cases where one or both collections contain null, and where collections themselves are null.

DisjointNullValues.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DisjointNullValues {

    public static void main(String[] args) {
        
        List<String> listWithNull = new ArrayList<>();
        listWithNull.add("A");
        listWithNull.add(null);
        listWithNull.add("B");
        
        List<String> listWithoutNull = new ArrayList<>();
        listWithoutNull.add("C");
        listWithoutNull.add("D");
        
        System.out.println("List with null vs without: " + 
            Collections.disjoint(listWithNull, listWithoutNull));
            
        List<String> anotherListWithNull = new ArrayList<>();
        anotherListWithNull.add(null);
        anotherListWithNull.add("E");
        
        System.out.println("Two lists with null: " + 
            Collections.disjoint(listWithNull, anotherListWithNull));
            
        try {
            Collections.disjoint(null, listWithoutNull);
        } catch (NullPointerException e) {
            System.out.println("Null collection error: " + e.getMessage());
        }
    }
}

When one collection contains null and the other doesn't, disjoint works normally. When both collections contain null, the method returns false because null is considered a common element.

Passing null as a collection parameter results in a NullPointerException. The method requires both parameters to be non-null collection instances.

disjoint Performance Considerations

This example demonstrates the performance characteristics of Collections.disjoint with different collection types. We'll compare HashSet and ArrayList to show the efficiency differences.

DisjointPerformance.java
package com.zetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DisjointPerformance {

    public static void main(String[] args) {
        
        // Create large collections
        List<Integer> bigList = new ArrayList<>();
        Set<Integer> bigSet = new HashSet<>();
        
        for (int i = 0; i < 1000000; i++) {
            bigList.add(i);
            bigSet.add(i + 1000000);
        }
        
        // Time disjoint check with List vs Set
        long startTime = System.nanoTime();
        boolean result = Collections.disjoint(bigList, bigSet);
        long endTime = System.nanoTime();
        
        System.out.println("List vs Set disjoint: " + result);
        System.out.println("Time taken: " + (endTime - startTime) + " ns");
        
        // Time disjoint check with Set vs Set
        Set<Integer> anotherSet = new HashSet<>();
        for (int i = 0; i < 1000000; i++) {
            anotherSet.add(i + 2000000);
        }
        
        startTime = System.nanoTime();
        result = Collections.disjoint(bigSet, anotherSet);
        endTime = System.nanoTime();
        
        System.out.println("Set vs Set disjoint: " + result);
        System.out.println("Time taken: " + (endTime - startTime) + " ns");
    }
}

The disjoint method is optimized to use the most efficient algorithm based on the collection types. When one collection is a Set, it uses the Set's fast contains() method (O(1) for HashSet). With two Lists, it must check each element (O(n*m)).

The output shows significantly better performance when at least one collection is a Set. This demonstrates the importance of choosing appropriate collection types for performance-critical operations.

Practical Use Case for disjoint

This example shows a practical application of Collections.disjoint in a real-world scenario. We'll use it to validate that a user's selected categories don't conflict with restricted categories.

DisjointPracticalExample.java
package com.zetcode;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class DisjointPracticalExample {

    public static void main(String[] args) {
        
        // Restricted categories for a user
        Set<String> restrictedCategories = new HashSet<>(
            Arrays.asList("Adult", "Violence", "Gambling"));
        
        // User-selected categories
        Set<String> userSelections = new HashSet<>(
            Arrays.asList("Sports", "News", "Education"));
        
        if (Collections.disjoint(restrictedCategories, userSelections)) {
            System.out.println("Selection valid: No restricted categories");
        } else {
            System.out.println("Invalid selection: Contains restricted categories");
        }
        
        // Try with invalid selection
        userSelections.add("Adult");
        if (Collections.disjoint(restrictedCategories, userSelections)) {
            System.out.println("Selection valid: No restricted categories");
        } else {
            System.out.println("Invalid selection: Contains restricted categories");
        }
    }
}

In this practical example, we use Collections.disjoint to validate user input against restricted categories. The first check passes because the user's selections don't include any restricted categories. The second check fails after adding a restricted category.

This demonstrates how disjoint can be used for validation in real applications. The method provides a clean, efficient way to check for prohibited items in user selections or configurations.

Source

Java Collections.disjoint Documentation

In this article, we've explored the Java Collections.disjoint method in depth. We've covered basic usage, different collection types, edge cases, performance considerations, and practical applications. Understanding this method helps efficiently check for common elements between collections.

Author

My name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts.

List all Java tutorials.