Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is Collections.disjoint in Java?

abhilash

The disjoint function in the Collections class is used to check whether any two specified collections are disjoint, i.e., whether the two collections have any elements in common or not.

Collections is defined in the util package in Java, so you must import the util package before you can use the disjoint function, as shown below.

import java.util.Collections;

Syntax

The syntax for the disjoint function is shown below.

Collections.disjoint(collection1, collection2)

Method signature

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

Parameters

  • Collection<?> c1: first collection
  • Collection<?> c2: second collection

Return value

The return value is a Boolean. The method returns true if there are no elements in common between the two collections; otherwise, it returns false.

Code

In the code below, we define two lists of strings that contain no elements in common. Hence, applying the disjoint method on the two lists results in true.

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

public class Main {

    public static void main(String[] args){

        List<String> collection1 = new ArrayList<>();
        collection1.add("one");
        collection1.add("two");
        collection1.add("three");

        List<String> collection2 = new ArrayList<>();
        collection1.add("nine");
        collection1.add("six");
        collection1.add("ten");

        System.out.println(Collections.disjoint(collection2, collection1));
    }
}

In the code below, we define two lists of integers that contain some elements in common. Hence, applying the disjoint method on the two lists results in false.

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

public class Main {

    public static void main(String[] args){
        List<Integer> collection1 = Arrays.asList(1, 2, 3, 4);
        List<Integer> collection2 = Arrays.asList(4, 5, 6);
        System.out.println(Collections.disjoint(collection1, collection2));
    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring