Common Elements Existence disjoint()

Common Elements Existence disjoint()

The method, disjoint(), of Collections class returns true if the two data structures under comparison does not have any elements in common. At least, one element is common in the both, it returns false. disjoint() method is very useful to compare (to know the existence of common elements) two lists or maps or sets.

Following is the method signature

  • static boolean disjoint(Collection col1, Collection col2): Returns true if the Collection classes (subclasses of Collection interface) col1 and col2 do not have any common elements. Introduced with JDK 1.5.
Example on Common Elements Existence disjoint()


Common Elements Existence disjoint()
Output screenshot on Common Elements Existence disjoint()

Three ArrayList objects firstList (with elements 10, 20, 30), secondList (with elements 60, 40, 20) and thirdList (with elements 60, 40, 50) are created. Observe the fristList does not have any common elements with thirdList. firstList and secondList have one common element 20 and similarly secondList and thirdList contain two elements in common, 60 and 40. Let us apply disjoint() method on these objects.

boolean exists = Collections.disjoint(firstList, secondList);

The disjoint() method returns a boolean value. As firstList and secondList contains one common element, the variable exists is given a false value.

Collections.disjoint(firstList, thirdList)

The above statement returns true as firstList and thirdList do not have any common elements.

Sets also can be checked for common elements.

Leave a Reply

Your email address will not be published. Required fields are marked *