Find Common Elements in Two Java Lists

In this article, we’ll introduce the method to find the common elements between two lists in Java.

Question

Supposing we have two lists, one list contains the elements we already have while the other contains the elements from incoming request. we want to determine which elements are common ones between these two lists.

oldList: a, b, c
newList: b, c, d
common: [b, c]

Plain Java

There is no explict way to do this, but we can bypass it by usingretainAll() method from List class to keep all common elements in the other list.

Note that retainAll() method will change the original list. Therefore, we need to create new List objects to hold the target data if necessary.

    private static void plainJava() {
        List<String> oldList = Arrays.asList("a", "b", "c");
        List<String> newList = Arrays.asList("b", "c", "d");
        List<String> newAdded = new ArrayList<>(newList);
        newAdded.removeAll(oldList);
        List<String> removed = new ArrayList<>(oldList);
        removed.removeAll(newList);
        log.info("newly added: {}, removed: {}", newAdded, removed);
    }

Java 8 Stream

Code gets more cleaner and readible when using Java Stream API.

    private static void javaStream() {
        List<String> list1 = Arrays.asList("a", "b", "c");
        List<String> list2 = Arrays.asList("b", "c", "d");
        List<String> common = list1.stream()
                .filter(list2::contains).collect(Collectors.toList());
        log.info("common: {}", common);
    }

Apache Common Collections

If you have Apache common collections in the project classpath, ListUtils.removeAll() an ListUtils.intersection() are options to merge 2 lists.

Both method accept two lists and return a new one, they won’t modify the original lists.

    private static void apacheCommonsCollectionsListUtils() {
        List<String> list1 = Arrays.asList("a", "b", "c");
        List<String> list2 = Arrays.asList("b", "c", "d");
        List<String> common = ListUtils.intersection(list1, list2);
        // an alternative
        // List<String> common = ListUtils.retainAll(list1, list2);
        log.info("common: {}", common);
    }

By the way, if you are working on Set, you can use SetUtils.difference()

    Set<String> common = SetUtils.intersection(set1, set2);

Google Guava

There is not handy method in Guava to get common elements between two lists, but there is method for Set class. To use Guava, we need to first convert our List to a Set:

    private static void googleGuavaSetsDifference() {
        List<String> list1 = Arrays.asList("a", "b", "c");
        List<String> list2 = Arrays.asList("b", "c", "d");
        Set<String> set1 = Sets.newHashSet(list1);
        Set<String> set2 = Sets.newHashSet(list2);
        Set<String> common = Sets.intersection(set1, set2);
        log.info("common: {}", common);
    }

Read More