Course contentsShow
← Java
Lesson 1265 of 2,87028. Collections Utility ClassFree lesson

Collections.disjoint: Testing Collection Intersection

Check if two collections have no common elements using disjoint(), returning true when sets are completely separate.

Collections.disjoint: Testing Collection Intersection

What you'll learn: How to quickly check whether two collections share any common elements using Collections.disjoint().

The Core Idea

Collections.disjoint(Collection<?> c1, Collection<?> c2) is a utility method that returns true if the two collections have no elements in common — meaning they're completely separate, with zero overlap. If even a single element appears in both collections, it returns false.

Think of it like two guest lists for different parties. If the lists are disjoint, no person is invited to both parties. If even one person appears on both lists, the sets intersect and are not disjoint.

How It Works

The method efficiently tests for intersection by iterating through one collection and checking membership in the other. It returns immediately when it finds a common element, making it fast in practice.

import java.util.*;

public class DisjointDemo {
    public static void main(String[] args) {
        List<String> teamA = Arrays.asList("Alice", "Bob", "Charlie");
        List<String> teamB = Arrays.asList("Diana", "Eve", "Frank");
        List<String> teamC = Arrays.asList("Charlie", "Grace", "Henry");
        
        // teamA and teamB share no members
        System.out.println(Collections.disjoint(teamA, teamB)); // true
        
        // teamA and teamC both have "Charlie"
        System.out.println(Collections.disjoint(teamA, teamC)); // false
        
        // Empty collections are disjoint from any collection
        System.out.println(Collections.disjoint(teamA, Collections.emptyList())); // true
    }
}

This is especially useful when validating that two sets of data don't overlap, such as checking that user permissions don't conflict or that test inputs are truly independent.

Key Takeaway: Use Collections.disjoint() to efficiently test whether two collections have no elements in common — it returns true only when the collections are completely separate.