List Intersection, Union, & Unique

Ever have two lists that you need to pull the unique elements from? Or need to pull the elements in both? Here is a ListUtils class for doing just those steps.

package name.mymiller.extensions.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author jmiller Provide a set of utilities to use on lists.
 */
public class ListUtils {

	/**
	 * Find the common elements between two Lists
	 * 
	 * @param <E> Type used in lists, which must have overridden equals();
	 * @param a   List A
	 * @param b   List B
	 * @return List<E> that contains the common elements between the Lists.
	 */
	public static <E> List<E> intersection(List<E> a, List<E> b) {
		return a.stream().distinct().filter(b::contains).collect(Collectors.toList());
	}

	/**
	 * Join two lists together to form a new List
	 * 
	 * @param <E> Type used in lists, which must have overridden equals();
	 * @param a   List A
	 * @param b   List B
	 * @return List<E> that contains the contents of both Lists.
	 */
	public static <E> List<E> union(List<E> a, List<E> b) {
		final List<E> unionList = new ArrayList<>(a);
		unionList.addAll(b);
		return unionList.stream().distinct().collect(Collectors.toList());
	}

	/**
	 * Create a list of the unique elements in both Lists.
	 * 
	 * @param <E> Type used in lists, which must have overridden equals();
	 * @param a   List A
	 * @param b   List B
	 * @return List<E> that contains the unique elements not shared between lists.
	 */
	public static <E> List<E> unique(List<E> a, List<E> b) {
		final List<E> unionList = ListUtils.union(a, b);
		unionList.removeAll(ListUtils.intersection(a, b));
		return unionList.stream().distinct().collect(Collectors.toList());
	}
}
Ghostprogrammer
  • Ghostprogrammer
  • I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: