CollectionUtils union() Example in Java

The CollectonsUtils.union() method is used to get the union of two lists. Consider we have two lists list1 and list2, which have different elements.

package com.javatute;

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

import org.apache.commons.collections4.CollectionUtils;

public class CollectionsUtilIsUnionCollection {
	public static void main(String[] args) {

		// Create first list
		List<String> list1 = new ArrayList<>();
		// add some element
		list1.add("John");
		list1.add("Mark");
		list1.add("Smith");
		list1.add("Twin");

		// create second list
		List<String> list2 = new ArrayList<>();
		// add some element
		list2.add("John");
		list2.add("Mark");
		list2.add("Smith");
		list2.add("Twin");
		list2.add("James");

		System.out.println(CollectionUtils.union(list1, list2));
	}
}

Output – [James, Smith, John, Mark, Twin]

Note – We need to add maven dependency in order to use CollectionUtils class.

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

That’s all about CollectionUtils union() Example in Java.

See CollectionUtils union() method docs.

You may like.