Collections disjoint method

In this post under Java Collections, I will show with example the purpose of Collections class static “disjoint” method.

This method compares two collections provided as input and returns true if both the collections have no elements in common.

For our example, we will use the below main class.

Main class

1  package core.collection;
2  
3  import java.util.ArrayList;
4  import java.util.Collections;
5  import java.util.List;
6  
7  public class CollectionDisjointDemo {
8      public static void main(String [] args) {
9          List<Integer> integerList1 = new ArrayList<>(0);
10         integerList1.add(1);
11         integerList1.add(2);
12         integerList1.add(3);
13         integerList1.add(4);
14         integerList1.add(5);
15 
16         List<Integer> integerList2 = new ArrayList<>(0);
17         integerList2.add(4);
18         integerList2.add(5);
19         integerList2.add(6);
20         integerList2.add(7);
21 
22         List<Integer> integerList3 = new ArrayList<>(0);
23         integerList3.add(6);
24         integerList3.add(7);
25         integerList3.add(8);
26         integerList3.add(9);
27 
28         boolean result = Collections.disjoint(integerList1, integerList2);
29         System.out.println("integerList1 vs integerList2: " + result);
30 
31         result = Collections.disjoint(integerList1, integerList3);
32         System.out.println("integerList1 vs integerList3: " + result);
33     }
34 }

In the above code, at line 9 I create an integer list named “integerList1” and populate it.

At line 16, I create another integer list named “integerList2” and populate it.

At line 22, I create another integer list named “integerList3” and populate it.

Now at line 28, I compare “integerList1” with “integerList2” using “Collections” class static method “disjoint”. Since both the list has some elements in common, the result will be false.

Now at line 31, I compare “integerList1” with “integerList3”. Since both the list has no elements in common, the result will be true.

In this way we can use “Collections” class “disjoint” method.

Leave a comment