CollectionUtils subtract() Example in Java

In this post, we will see org.apache.commons.lang3.CollectionUtils subtract() example in Java. Consider we have two lists of Strings, and we want to subtract the second list from the first list, i.e., we want to remove all the elements of the second list from the first list.

CollectionUtils subtract() Example in Java

import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;

public class SubtractExample {

    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        list1.add("apple");
        list1.add("banana");
        list1.add("orange");
        list1.add("grapes");
        
        List<String> list2 = new ArrayList<>();
        list2.add("banana");
        list2.add("grapes");
        
        Collection<String> result = CollectionUtils.subtract(list1, list2);
        
        System.out.println(result); // Output: [apple, orange]
    }
}

In the above example, we first created two lists list1 and list2 of Strings. We added some elements to both lists.

Then, we used the subtract() method from the CollectionUtils class to remove all the elements of list2 from list1. The subtract() method returns a new Collection containing the elements that are in the first list but not in the second list.

Finally, we printed the updated result using the System.out.println() method, and the output was [apple, orange], which means the subtract() method removed the elements "banana" and "grapes" from list1.

We need to add the below dependency in maven to use org.apache.commons.lang3.CollectionUtils subtract() 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>

Another example of CollectionUtils subtract() method

package com.javatute;

import org.apache.commons.collections4.CollectionUtils;

import java.util.*;
public class CollectionUtilsSubtractExample {
    public static void main(String[] args) {
        List<String> l1 = Arrays.asList("Army", "Ant", "Air", "Car", "Book", "Bat");
        List<String> l2 = Arrays.asList("Army", "Aux", "Bat", "Book");

        System.out.println("L 1: " + l1);
        System.out.println("L 2: " + l2);
        System.out.println("L 1 - List 2: " + CollectionUtils.subtract(l1, l2));
    }
}

Output is

L 1: [Army, Ant, Air, Car, Book, Bat]
L 2: [Army, Aux, Bat, Book]
L 1 – List 2: [Ant, Air, Car]

Note:- This method is used to remove common data of the list that’s you want.

Related post.