CollectionUtils isSubCollection() Example in Java

In this post, we will see org.apache.commons.lang3.CollectionUtils isSubCollection() example in Java. The CollectionUtils.isSubCollection() method from Apache Commons Collections library in Java is used to check if one collection is a sub-collection of another collection. Let’s see an example.

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

public class SubCollectionExample {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);

        List<Integer> list2 = new ArrayList<>();
        list2.add(2);
        list2.add(3);

        boolean isSubCollection = CollectionUtils.isSubCollection(list2, list1);

        System.out.println("List2 is a sub-collection of List1: " + isSubCollection);
    }
}

Output is

List2 is a sub-collection of List1: true

This is because list2 is a subset of list1, meaning that all the elements in list2 are also present in list1. Therefore, the isSubCollection() method returns true.

In this example, we create two List objects, list1 and list2. We add elements to list1 and a subset of list1 to list2. We then use the isSubCollection() method to check if list2 is a sub-collection of list1. The method returns a boolean value indicating whether list2 is a sub-collection of list1 or not.

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

CollectionUtils isSubCollection() Example in Java

See docs.

Related post.