Use Collection#retainAll().

listA.retainAll(listB);
// listA now contains only the elements which are also contained in listB.

If you want to avoid that changes are being affected in listA, then you need to create a new one.

List<Integer> common = new ArrayList<>(listA);
common.retainAll(listB);
// common now contains only the elements which are contained in listA and listB.

If you're a fan of streams, best what you could do is to Stream#filter() on Collection#contains() of the other list.

List<Integer> common = listA.stream().filter(listB::contains).toList();
// common now contains only the elements which are contained in listA and listB.

It's only at least twice slower.

Answer from BalusC on Stack Overflow
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › compare two lists in java: equality, differences, common items
Compare Two Lists in Java: Equality, Differences, Common Items
2 weeks ago - Compare two lists in Java with equals() or ignoring order, count duplicates correctly, and find additional, missing and common items with removeAll(). ... Two lists in Java are equal when list1.equals(list2) returns true, which happens only ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › find-common-elements-in-two-arraylists-in-java
Find common elements in two ArrayLists in Java - GeeksforGeeks
August 26, 2026 - We can convert the first list into a stream and use the filter() method to keep only those elements that are present in the second list. ... The filter() method checks each element of list1.
🌐
Baeldung
baeldung.com › home › java › java list › check if a list contains an element from another list in java
Check if a List Contains an Element From Another List in Java | Baeldung
May 7, 2025 - In this tutorial, we’ll look at several methods in Java for checking if an element in one List is also present in another. We’ll explore various ways how to achieve it using Java Streams, Collections disjoint(), and Apache Commons.
🌐
Coderanch
coderanch.com › t › 743146 › java › Find-common-elements-lists-list
Find common elements between 2 lists where list elements are objects (Features new in Java 8 forum at Coderanch)
June 8, 2021 - The list can contain many elements but irrespective of the size, I am wondering if a better solution exist using FP. ... There are three kinds of actuaries: those who can count, and those who can't. ... I'll have to think about your question a bit, but I noticed right away your use of "float".
🌐
amitph
amitph.com › home › java › comparing two lists in java
Comparing Two Lists In Java - amitph
November 22, 2024 - We can use the equals() method from the List interface to compare two Java Lists for equality. As per the documentation, the equals() method returns true if: Both Lists contain the same elements in the same order.
🌐
Rip Tutorial
riptutorial.com › finding common elements between 2 lists
Java Language Tutorial => Finding common elements between 2 lists
public static void main(String[] args) { List<Integer> numbersA = new ArrayList<>(); List<Integer> numbersB = new ArrayList<>(); numbersA.addAll(Arrays.asList(new Integer[] { 1, 3, 4, 7, 5, 2 })); numbersB.addAll(Arrays.asList(new Integer[] { 13, 32, 533, 3, 4, 2 })); System.out.println("A: " + numbersA); System.out.println("B: " + numbersB); List<Integer> numbersC = new ArrayList<>(); numbersC.addAll(numbersA); numbersC.retainAll(numbersB); System.out.println("List A : " + numbersA); System.out.println("List B : " + numbersB); System.out.println("Common elements between A and B: " + numbersC); }
Find elsewhere
🌐
Techie Delight
techiedelight.com › find-common-elements-two-lists-java
Find common elements in two lists in Java | Techie Delight
Techie Delight is a leading platform for technical interview preparation. Prepare for your coding interview with Techie Delight. Improve your algorithmic skills and crack interviews with top tech companies.
🌐
YouTube
youtube.com › watch
How to Find common elements between two lists in Java
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Baeldung
baeldung.com › home › java › java list › finding the differences between two lists in java
Finding the Differences Between Two Lists in Java | Baeldung
April 29, 2026 - We should also note that if we want to find the common elements between the two lists, List also contains a retainAll method. A Java Stream can be used for performing sequential operations on data from collections, which includes filtering the differences between lists:
🌐
DevQA
devqa.io › java-compare-two-arraylists
Java Compare Two Lists
March 17, 2020 - public class CompareTwoArrayLists { public static void main(String[] args) { ArrayList<Integer> listOne = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); ArrayList<Integer> listTwo = new ArrayList<>(Arrays.asList(1, 2, 4, 5, 6, 7)); ...
Top answer
1 of 3
2

If you want to ignore the requirement of using a Set, you could use Java 8 Streams to solve the problem.

public static int numInCommon(List<Integer> list1, List<Integer> list2) {
    return (int) list1.stream()
        .distinct()
        .filter(i -> list2.contains(i))
        .count()
}

This is a four-step process:

  • Get a stream of list1 (if you are not used to streams you can think of this as a loop, but in reality a call to .stream() by itself is not looping)
  • Use .distinct() to ignore duplicate elements (that is, if the first list contains a number multiple times, it only processes it once. The .distinct() part uses a Set internally to keep track of which elements it has seen.
  • Use .filter to only keep the numbers that also occur in the second list.
  • .count() to count the number of seen elements. This returns a long which is why the entire result is typecast to an int here.

It's not until you call .count() that the loop is actually performed, this is because .count() is a "terminal operation".

I would recommend to read more about Streams on Oracle's website

2 of 3
5

I personally would shorten this greatly:

public static int numInCommon(List<Integer> list1, List<Integer> list2){
    if(list1.isEmpty() || list2.isEmpty()){
        return 0;
    }

    Set<Integer> setCommon = new HashSet<>(list1);
    setCommon.retainAll(list2);
    return setCommon.size();
}

Returning 0 at the start is good, but no need for the else block on the If code. Next task is to calculate the common elements - putting list1 into the set removes duplicates and then retainAll removes anything that isn't in list2. This leaves everythin in list1 and list2 without duplicates. Returning the size() counts the elements.

For performance - I'm taking the major assumption that HashSet is one of the quickest ways to check if an item exists and handle removal.

🌐
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. For more details, review our guide to Java 8’s Collectors. What if our Lists don’t contain Strings but rather instances of a custom class we’ve created?
Top answer
1 of 16
480

If you care about order, then just use the equals method:

list1.equals(list2)

From the javadoc:

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

If you want to check independent of order, you could copy all of the elements to Sets and use equals on the resulting Sets:

public static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
    return new HashSet<>(list1).equals(new HashSet<>(list2));
}

A limitation of this approach is that it not only ignores order, but also frequency of duplicate elements. For example, if list1 was ["A", "B", "A"] and list2 was ["A", "B", "B"] the Set approach would consider them to be equal.

If you need to be insensitive to order but sensitive to the frequency of duplicates you can either:

  • sort both lists (or copies) before comparing them, as done in this answer to another question
  • or copy all elements to a Multiset
2 of 16
117

I posted a bunch of stuff in comments I think it warrants its own answer.

As everyone says here, using equals() depends on the order. If you don't care about order, you have 3 options.

Option 1

Use containsAll(). This option is not ideal, in my opinion, because it offers worst case performance, O(n^2).

Option 2

There are two variations to this:

2a) If you don't care about maintaining the order ofyour lists... use Collections.sort() on both list. Then use the equals(). This is O(nlogn), because you do two sorts, and then an O(n) comparison.

2b) If you need to maintain the lists' order, you can copy both lists first. THEN you can use solution 2a on both the copied lists. However this might be unattractive if copying is very expensive.

This leads to:

Option 3

If your requirements are the same as part 2b, but copying is too expensive. You can use a TreeSet to do the sorting for you. Dump each list into its own TreeSet. It will be sorted in the set, and the original lists will remain intact. Then perform an equals() comparison on both TreeSets. The TreeSetss can be built in O(nlogn) time, and the equals() is O(n).

Take your pick :-).

EDIT: I almost forgot the same caveat that Laurence Gonsalves points out. The TreeSet implementation will eliminate duplicates. If you care about duplicates, you will need some sort of sorted multiset.

🌐
Sololearn
sololearn.com › en › Discuss › 2915013 › check-if-two-lists-have-atleast-one-element-common
Check if two lists have at-least one element common | Sololearn: Learn to code for FREE!
U can use for loop on one of them and check if any element exists in the other list OR u can use function a =[1,8,2,4,5] b=[2,6,7,8,9] count = 0 for ele in a: if ele in b: count += 1 continue if count >= 1: print ("True") print ("False") 31st ...
🌐
Quora
quora.com › How-do-I-find-the-common-elements-between-two-arrays-in-Java
How to find the common elements between two arrays in Java - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.