CollectionUtils disjunction() Example in Java

The disjunction() method of the CollectionUtils class is used to return the disjunction of two collections, which is the set of elements that are in either one of the collections but not in both. In this post, we will see org.apache.commons.lang3.CollectionUtils disjunction() example in Java.

Here’s an example of CollectionUtils disjunction() method in Java

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

public class CollectionUtilsDisjunctionExample {
  public static void main(String[] args) {
    List<String> list1 = new ArrayList<>();
    list1.add("A");
    list1.add("B");
    list1.add("C");
    
    List<String> list2 = new ArrayList<>();
    list2.add("B");
    list2.add("C");
    list2.add("D");
    
    List<String> disjunction = (List<String>) CollectionUtils.disjunction(list1, list2);
    System.out.println("Disjunction: " + disjunction);
  }
}

Output – Disjunction: [A, D]

In this example, the disjunction of the two lists list1 and list2 is calculated, and the result is stored in a list named disjunction.

We need to add the below dependency in the pom.xml to use org.apache.commons.lang3.CollectionUtils disjunction() method. We can download apache-commons maven dependency from here.

pom.xml changes

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>

Summary –

The disjunction() method of the CollectionUtils class in Apache Commons Collections library is often used in Java to find the set of elements that are in either one of two collections but not in both.

Here are some common uses of the disjunction() method:

  1. Comparing two lists: You can use the disjunction() method to compare two lists and find the elements that are unique to each list.
  2. Filtering data: You can use the disjunction() method to filter data based on the presence of elements in one collection but not in another

That’s all about CollectionUtils disjunction() example in Java.

Related post.