Collections.disjoint Checks No Common Elements

Decide whether two collections share nothing with Collections.disjoint, one call instead of nested loops, with an empty collection always reporting true.

JavaData Integrity

Code

snippet
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class GuestListCheck {

    public static void main(String[] args) {
        Set<String> vipGuests = Set.of("ada", "linus", "grace");
        List<String> tonight = List.of("ken", "ada", "margaret");

        // 两个集合没有共同元素时返回 true:ada 同时出现在两边
        System.out.println("vip ∩ tonight empty: " + Collections.disjoint(vipGuests, tonight));

        List<String> standby = List.of("ken", "margaret");
        System.out.println("vip ∩ standby empty: " + Collections.disjoint(vipGuests, standby));

        // 空集合与任何集合都"无共同元素",不需要先做 size 检查
        System.out.println("vip ∩ empty: " + Collections.disjoint(vipGuests, List.of()));

        // 只判有无走 disjoint;要列出具体冲突元素时才自己求交集
        if (!Collections.disjoint(vipGuests, tonight)) {
            System.out.println("resolve overlap before seating");
        }
    }
}

How it works

Everything happens inside the class GuestListCheck and the function main.

Points of care

  • Runs with what the toolchain already gives you — nothing extra.

Putting it to use

Entry signature: public static void main(String[] args)

The demo output is labeled (vip ∩ tonight empty:, vip ∩ standby empty:, vip ∩ empty:); each label names the call that printed it.

Core lines

List<String> tonight = List.of("ken", "ada", "margaret");
Set<String> vipGuests = Set.of("ada", "linus", "grace");
List<String> standby = List.of("ken", "margaret");

Interactive Tools for This Topic

FAQ

What does Collections.disjoint Checks No Common Elements print when run?
Run it as a complete program — the output lines carry labels such as `vip ∩ tonight empty:`, `vip ∩ standby empty:`, `vip ∩ empty:`.