Here's a plain implementation without using any third-party library. Main advantage over retainAll, removeAll and addAll is that these methods don't modify the original lists input to the methods.

public class Test {

    public static void main(String... args) throws Exception {

        List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
        List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));

        System.out.println(new Test().intersection(list1, list2));
        System.out.println(new Test().union(list1, list2));
    }

    public <T> List<T> union(List<T> list1, List<T> list2) {
        Set<T> set = new HashSet<T>();

        set.addAll(list1);
        set.addAll(list2);

        return new ArrayList<T>(set);
    }

    public <T> List<T> intersection(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();

        for (T t : list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }
}
Answer from adarshr on Stack Overflow
Top answer
1 of 16
151

Here's a plain implementation without using any third-party library. Main advantage over retainAll, removeAll and addAll is that these methods don't modify the original lists input to the methods.

public class Test {

    public static void main(String... args) throws Exception {

        List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
        List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));

        System.out.println(new Test().intersection(list1, list2));
        System.out.println(new Test().union(list1, list2));
    }

    public <T> List<T> union(List<T> list1, List<T> list2) {
        Set<T> set = new HashSet<T>();

        set.addAll(list1);
        set.addAll(list2);

        return new ArrayList<T>(set);
    }

    public <T> List<T> intersection(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();

        for (T t : list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }
}
2 of 16
139

Collection (so ArrayList also) have:

col.retainAll(otherCol) // for intersection
col.addAll(otherCol) // for union

Use a List implementation if you accept repetitions, a Set implementation if you don't:

Collection<String> col1 = new ArrayList<String>(); // {a, b, c}
// Collection<String> col1 = new TreeSet<String>();
col1.add("a");
col1.add("b");
col1.add("c");

Collection<String> col2 = new ArrayList<String>(); // {b, c, d, e}
// Collection<String> col2 = new TreeSet<String>();
col2.add("b");
col2.add("c");
col2.add("d");
col2.add("e");

col1.addAll(col2);
System.out.println(col1); 
//output for ArrayList: [a, b, c, b, c, d, e]
//output for TreeSet: [a, b, c, d, e]
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › intersection-of-two-arrays
Intersection of two Arrays - GeeksforGeeks
import java.util.HashSet; import java.util.ArrayList; class GfG { // Function to find intersection of two arrays static ArrayList<Integer> intersect(int[] a, int[] b) { // Put all elements of a[] in sa HashSet<Integer> sa = new HashSet<>(); for (int num : a) { sa.add(num); } ArrayList<Integer> res = new ArrayList<>(); // Traverse through b[] for (int num : b) { // If the element is in sa if (sa.contains(num)) { res.add(num); // Add it to the result array sa.remove(num); // Erase it from sa to avoid duplicates } } return res; } public static void main(String[] args) { int[] a = {1, 2, 3, 2, 1}; int[] b = {3, 2, 2, 3, 3, 2}; ArrayList<Integer> res = intersect(a, b); for (int val : res) { System.out.print(val + " "); } } } Python ·
Published: July 27, 2025
Discussions

java - Find intersection between two ArrayLists - Stack Overflow
Find intersection of two ArrayLists of Strings. Here is the code: public ArrayList intersection( ArrayList AL1, ArrayList AL2){ ArrayList More on stackoverflow.com
🌐 stackoverflow.com
October 7, 2014
Intersection between two arraylist Java - Stack Overflow
I wanted to find an intersection between two arraylist that are of byte[] format and return the common indices. I have the code as follows and it works correctly: ArrayList intersec... More on stackoverflow.com
🌐 stackoverflow.com
java - Find the intersection of ArrayList elements inside an ArrayList - Code Review Stack Exchange
ArrayList is a specific implementation, when List is the general concept. String, the name of a common class in the JDK, and written in PascalCase, is a terrible choice for a generic type token in this code: public List intersection(List list1, List list2) { ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 15, 2017
Intersection of Two Dimensional ArrayList in Java - Stack Overflow
I want to intersection list1, list2 and list3 in a ArrayList. So, I want to intersection ArrayLists of arrayList2D. arrayList2D can contain (max) six ArrayList. How I can do? That's intersection... More on stackoverflow.com
🌐 stackoverflow.com
🌐
ThisCodeWorks
thiscodeworks.com › union-and-intersection-of-two-arraylists-java › 62ea3573a0e8080015c7c31f
Union and intersection of two ArrayLists | thiscodeWorks
import java.util.*; public class UnionIntersectionOfTwoListsExample { public static void main (String[] args) { List<String> list1 = new ArrayList<String>(Arrays.asList("a","b","c","d","e")); List<String> list2 = new ArrayList<String>(Arrays.asList("b","d","f","g")); //Find union of two lists System.out.println("Union of List1 and List2 :" + getUnionOfLists(list1, list2)); //Find intersect of lists using Stream API (Java 8) System.out.println("Intersection of List1 & List2 Method 1: " + getIntersectOfLists1(list1, list2)); //Find intersect of lists using retainAll() method System.out.println("
🌐
Stack Overflow
stackoverflow.com › questions › 50956396 › intersection-between-two-arraylist-java
Intersection between two arraylist Java - Stack Overflow
public <T> List<T> intersection(List<T> list1, List<T> list2) { List<T> list = new ArrayList<T>(); for (T t : list1) { if(list2.contains(t)) { list.add(t); } } return list; } Reference: Intersection and union of ArrayLists in Java
🌐
Java Guides
javaguides.net › 2024 › 05 › java-find-intersection-of-two-lists.html
Java: Find Intersection of Two Lists
May 29, 2024 - One way to find the intersection of two lists is by iterating through each list and collecting the common elements. import java.util.ArrayList; import java.util.List; public class ListIntersectionExample { public static void main(String[] args) ...
🌐
Madhur Ahuja
madhur.co.in › posts › union and intersection of arraylist in java
Union and Intersection of ArrayList in Java | Madhur Ahuja
July 29, 2014 - import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C")); List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F")); list1.retainAll(list2) ; System.out.println(list1); System.out.println(list2); } }
Find elsewhere
Top answer
1 of 1
1

Approaching programming interview questions

One of the most important things during programming interviews is clarifying the problem. If the task is intersection of lists as opposed to sets, an important question is how to handle duplicate values.

For example, the current implementation is buggy. The intersection method will return a,a,a for the input a,a,a and a,a, but it will give a,a for the input a,a and a,a,a. The logical assumption would be that it should always return a,a regardless of the order of parameters. Then again, you should not just assume things, you should ask for the expected behavior, or at least state your assumptions loud and clear.

And if there can be no duplicates in the inputs, then why aren't they sets instead of lists?

Why is ArrayList specified instead of just List? ArrayList is a specific implementation, when List is the general concept.

Generic type tokens

String, the name of a common class in the JDK, and written in PascalCase, is a terrible choice for a generic type token in this code:

public <String> List<String> intersection(List<String> list1, List<String> list2) {
    List<String> list = new ArrayList<String>();

    for (String t: list1) {
        if(list2.contains(t)) {
            list.add(t);
        }
    }

    return list;
}

It should have been written like this:

public static <T> List<T> intersection(List<T> list1, List<T> list2) {
    List<T> list = new ArrayList<>();

    for (T t : list1) {
        if (list2.contains(t)) {
            list.add(t);
        }
    }

    return list;
}

Intersection of many lists

But how do I make it work for multiple ArrayLists inside one ArrayList?

I'm not sure I get what's blocking you. Perhaps you mean, instead of the intersection of 2 lists, how to intersect more than 2?

In that case, that's an interesting question to discuss about, and consider different alternatives, starting from simple (brute force) techniques, and then trying to improve.

Simple solution: if you have n lists, you could intersect the first 2, then intersect the result with the 3rd, then intersect the result with the 4th, and so on, until the last. The final result will be the intersection of all the lists, reachable in n - 1 steps.

Is it possible to do better?

  • Hint 1: consider the concept of divide and conquer.
  • Hint 2: how does merge sort work?
🌐
Baeldung
baeldung.com › home › java › java list › intersection of two lists in java
Intersection of Two Lists in Java | Baeldung
April 4, 2025 - The intersection should contain each common element only once. The order shouldn’t matter, thus toSet is the most straightforward choice, but we can also use toList or another collector method.
Top answer
1 of 2
1

The intersection of two lists is done using the retainAll() method.

It update the list, so if you don't want that, you should copy the list first.

If you have more than 2 lists, you copy the first and then call retainAll() for each of the remaining lists.

ArrayList<ArrayList<String>> lists = ...

List<String> intersection = new ArrayList<>(lists.get(0));
for (List<String> list : lists.subList(1, lists.size()))
    intersection.retainAll(list);

However performance will be a bad O(n*m), where n and m are the sizes of the two largest lists.

That is because retainAll() does a contains() against the list given in the parameter, which is a sequential search, for each element in the intersection list.

Performance can be improved to O(n), where n is the largest list, by converting the lists to sets.

List<String> intersection = new ArrayList<>(lists.get(0));
for (List<String> list : lists.subList(1, lists.size()))
    intersection.retainAll(new HashSet<>(list));

In Java 8+, the for loop can be simplified to one of these:

lists.subList(1, lists.size()).stream().map(HashSet::new).forEach(intersection::retainAll);

lists.subList(1, lists.size()).forEach(list -> intersection.retainAll(new HashSet<>(list)));
2 of 2
1

i would use the list.retainAll method as in

private ArrayList<String> getIntersection(ArrayList<ArrayList<String>> lists) {
    if(null == lists || lists.isEmpty()) {
        return null;
    }
    ArrayList<String> intersection = lists.get(0);
    lists.forEach(intersection::retainAll);
    return intersection;
}
🌐
Stepinjava
javavisit.wordpress.com › 2012 › 09 › 20 › a-union-b-and-a-intersection-b-for-two-arraylists
A Union B and A intersection B for two ArrayLists. | Stepinjava
September 20, 2012 - public class Test { public static void main(String... args) throws Exception { List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C")); List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F")); System.out.println(new Test().intersection(list1, list2)); System.out.println(new Test().union(list1, list2)); } public <T> List<T> union(List<T> list1, List<T> list2) { Set<T> set = new HashSet<T>(); set.addAll(list1); set.addAll(list2); return new ArrayList<T>(set); } public <T> List<T> intersection(List<T> list1, List<T> list2) { List<T> list = new ArrayList<T>(); for (T t : list1) { if(list2.contains(t)) { list.add(t); } } return list; } } ------------------------------------------------------------------------- output: ... Like Loading... ... A Union B and A intersection B for two ArrayLists.
🌐
LeetCode
leetcode.com › problems › intersection-of-two-arrays
Intersection of Two Arrays - LeetCode
Can you solve this real interview question? Intersection of Two Arrays - Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
🌐
Blogger
massivealgorithms.blogspot.com › 2014 › 09 › intersection-of-two-arraylists-epi.html
Massive Algorithms: Intersection of two ArrayLists - EPI
September 16, 2014 - https://github.com/epibook/epibook.github.io/blob/master/solutions/java/src/main/java/com/epi/IntersectSortedArrays3.java public static List<Integer> intersect(List<Integer> A, List<Integer> B) { List<Integer> intersect = new ArrayList<>(); int i = 0; int j = 0; while (i < A.size() && j < B.size()) { if (A.get(i).equals(B.get(j)) && (i == 0 || !A.get(i).equals(A.get(i - 1)))) { intersect.add(A.get(i)); ++i; ++j; } else if (A.get(i) < B.get(j)) { ++i; } else { // A.get(i) > B.get(j).
🌐
Stack Overflow
stackoverflow.com › questions › 26189191 › what-kind-of-helper-method-would-i-need-to-find-an-intersection-between-two-arra
java - What kind of helper method would I need to find an intersection between two arraylists?! (recursion only) - Stack Overflow
CopyArrayList A1 = new ArrayList(); ArrayList A2 = new ArrayList(); A1.add("a"); A1.add("b"); A1.add("c"); A2.add("b"); A2.add("c"); A2.add("d"); A2.add("e"); ArrayList intersect = Practice.intersection(A1,A2); System.out.println(A1 + " intersect " + A2 + " = " + intersect);
🌐
javaspring
javaspring.net › blog › intersection-and-union-of-arraylists-in-java
How to Compute Intersection and Union of ArrayLists in Java: Methods for File Filtering (AND/OR), Optimal Data Structures, and Runtime Efficiency — javaspring.net
For example, suppose you have two lists of files: one filtered by "modified in 2024" and another by "size > 1MB". The intersection would give files that are both modified in 2024 and larger than 1MB (AND filter), while the union would give files that are either modified in 2024 or larger than 1MB (OR filter). This blog dives deep into computing intersections and unions for ArrayLists in Java.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-find-the-intersection-between-two-collection
Java Program to Find the Intersection Between Two Collection - GeeksforGeeks
July 23, 2025 - In this article we will use two ... and ArrayList class to find the intersection between the two collection. ... Store the elements in the First collection and in the second collection (Array List).
🌐
Medium
medium.com › @shaswata.ssaha › efficiently-finding-the-intersection-of-two-arrays-in-java-ce8b6c08c0ec
Efficiently Finding the Intersection of Two Arrays in Java | by Shaswata Saha | Medium
July 2, 2024 - To solve this problem, we need to find common elements between two arrays and ensure that each common element appears in the result as many times as it appears in both input arrays.
🌐
Medium
medium.com › @alxkm › how-to-find-intersection-and-difference-between-two-sets-or-lists-in-java-5a873a8bff5d
Java Interview: How to Find Intersection and Difference Between Two Sets or Lists in Java | by Alex Klimenko | Medium
August 9, 2025 - List<String> intersection = new ArrayList<>(); for (String item : list1) { if (list2.contains(item)) { intersection.add(item); } } System.out.println("Intersection: " + intersection);