CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8\’s Stream API.

    Checking union

    union() method of CollectionUtils can be used to get the union of two collections.

    Declaration

    Following is the declaration for

    org.apache.commons.collections4.CollectionUtils.union() method

    1. public static <O> Collection<O> union(Iterable<? extends O> a,
    2. Iterable<? extends O> b)

    Parameters

    • a − The first collection, must not be null.

    • b − The second collection, must not be null.

    Return Value

    The union of the two collections.

    Example

    The following example shows the usage of org.apache.commons.collections4.CollectionUtils.union() method. We\'ll get the union of two lists.

    1. import java.util.Arrays;
    2. import java.util.List;
    3.  
    4. import org.apache.commons.collections4.CollectionUtils;
    5.  
    6. public class CollectionUtilsTester {
    7. public static void main(String[] args) {
    8. //checking inclusion
    9. List<String> list1 = Arrays.asList("A","A","A","C","B","B");
    10. List<String> list2 = Arrays.asList("A","A","B","B");
    11.  
    12. System.out.println("List 1: " + list1);
    13. System.out.println("List 2: " + list2);
    14. System.out.println("Union of List 1 and List 2: "
    15. + CollectionUtils.union(list1, list2));
    16. }
    17. }

    Output

    It will print the following result.

    1. List 1: [A, A, A, C, B, B]
    2. List 2: [A, A, B, B]
    3. Union of List 1 and List 2: [A, A, A, B, B, C]