The simplest solution would be to use sets, as long as you don't care that the elements in the result will have a different order, and that duplicates will be removed. The input arrays array1 and array2 are the Integer[] subarrays of the given int[] arrays corresponding to the number of elements that you intend to process:

Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(array1));
Set<Integer> s2 = new HashSet<Integer>(Arrays.asList(array2));
s1.retainAll(s2);

Integer[] result = s1.toArray(new Integer[s1.size()]);

The above will return an Integer[], if needed it's simple to copy and convert its contents into an int[].

Answer from Óscar López on Stack Overflow
🌐
How to do in Java
howtodoinjava.com › home › java array › intersection of two arrays in java
Intersection of Two Arrays in Java
February 22, 2023 - To get the intersection of two arrays, follow these steps: Push the first array in a HashSet. Use retainAll() method to retain only elements which are present in the second array.
🌐
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 - Find Intersection: Iterate over nums2 and check if the element exists in the HashMap with a count greater than zero. If it does, add it to the result list and decrement the count in the map.
🌐
Baeldung
baeldung.com › home › java › java array › intersection between two integer arrays
Intersection Between Two Integer Arrays| Baeldung
March 17, 2024 - In this article, we’ve seen how to use the contains and remove methods to implement an intersection for two arrays in Java.
🌐
Web Rewrite
webrewrite.com › find-intersection-two-arrays
Find Intersection of Two Arrays | Java | Multiple Approaches
April 29, 2022 - i) Use two index variables i and j, initialize them with 0. ii) If element present at arr1[i] is smaller than arr2[j] then increment i. iii) If arr1[i] is greater than arr2[j] then increment j. iv) If both are same then print any of the array ...
🌐
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.
🌐
Medium
medium.com › @vinobabu.t › intersection-of-two-arrays-two-different-java-solutions-6b86ba3a46a1
Intersection of Two Arrays — Two Different Java Solutions | by Vino Babu Thomas | Medium
March 10, 2024 - This approach finds the intersection of two arrays by using two sets. It first adds all elements from the first array to a set, then iterates over the second array and adds any element that is also in the first set to a result set.
🌐
Sololearn
sololearn.com › en › Discuss › 1627015 › intersection-array-from-two-arrays-java
Intersection array from two arrays, Java. | Sololearn: Learn to code for FREE!
There are some errors in your code 1. for (int i = 0; i < arr.length; i++) { ===> for (int i = 0; i < arr1.length; i++) { 2. if (list[i] == list1[j]) { ==> if (arr1[i] == arr2[j]) { 3. common[k] = list[i]; ==> common[k] = arr1[i]; 4. Add one more } at the end Nevertheless the problem still exists. Numbers are duplicated in the array. I believe that you want the distincts. https://code.sololearn.com/cvi3k6mqfm12/#java Keep in mind that in the above code I use 4 positions as a size of common array.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › article › How-to-find-the-intersection-of-two-arrays-in-java
How to find the intersection of two arrays in java?
Within the second loop compare the elements of the two arrays: public class IntersectionOfTwoArrays { public static void main(String args[]) { int myArray1[] = {23, 36, 96, 78, 55}; int myArray2[] = {78, 45, 19, 73, 55}; System.out.println("Intersection of the two arrays ::"); for(int i = 0; i<myArray1.length; i++ ) { for(int j = 0; j<myArray2.length; j++) { if(myArray1[i]==myArray2[j]) { System.out.println(myArray2[j]); } } } } }
🌐
Blogger
javahungry.blogspot.com › 2013 › 12 › intersection-of-two-arrays-in-java-code-with-example.html
Intersection of two arrays in java with example | Java Hungry
public class Intersection { /** * @param args */ static int i,j,k,c=0,w; public static void main(String[] args) { int[] x= {2,5,3,7}; System.out.println("The first array is " +" "); for(int i=0;i;x.length;i++) System.out.print(x[i]+" "); System.out.println(""); int[] y={5,2,9,0,1}; System.out.println("The second array is " +" "); for(int j=0;j;y.length;j++) System.out.print(y[j]+" "); System.out.println(""); intersection(x,y); } static void intersection(int x[],int y[]) { int []z=new int[x.length+y.length]; for(i=0;i <(x.length);i++) { for(j=0;j < y.length;j++) { if(x[i]==y[j]) { z[c]=x[i]; c++; } else continue; } } System.out.println("Intersection of two array is " +" "); for(k=0;k < c;k++) { System.out.print(" "+z[k]+" "); } System.out.println(" "); } } ... Subham Mittal has worked in Oracle for 3 years. Enjoyed this post? Never miss out on future posts by subscribing JavaHungry
Top answer
1 of 16
108
foreach element e in array A
    insert e into hash table H

foreach element e in array B
    if H contains e 
        print e

This algorithm is O(N) in time and O(N) in space.

To avoid the extra space, you can use the sorting based approach.

2 of 16
32

The lower bound on efficiency is O(n) - you need to at least read all the elements. Then there are several apporaches:

Dumb simplest approach

Search for every element from array one in array two. Time complexity O(n^2).

Sorting approach

You need to sort only array one, then search for elements from array two using binary search. Time complexity: sorting O(nlogn), searching O(n * logn) = O(nlogn), total O(nlogn).

Hash approach

Create a hash table from array one elements. Search for elements form second table in the hash table. The time complexity depends on the hash function. You can achieve O(1) for searches in the optimal case (all elements will have different hash value), but O(n) in the worst case (all elements will have the same hash value). Total time complexity: O(n^x), where x is a factor of hash function efficiency (between 1 and 2).

Some hash functions are guaranteed to build a table with no collisions. But the building no longer takes strictly O(1) time for every element. It will be O(1) in most cases, but if the table is full or a collision is encountered, then the table needs to be rehashed - taking O(n) time. This happens not so often, much less frequently than clean adds. So the AMORTISED time complexity is O(1). We don't care about some of the adds taking O(n) time, as long as the majority of adds takes O(1) time.

But even so, in an extreme case, the table must be rehashed every single insertion, so the strict time complexity would be O(n^2)

🌐
Scaler
scaler.com › home › topics › intersection of two arrays
Intersection of Two Arrays - Scaler Topics
October 12, 2022 - DSA Problem Solving for Interviews ... The task is to find the intersection of elements of Arr1 and Arr2. The intersection is the list of common and distinct elements between Arr1 and Arr2....
🌐
Java2s
java2s.com › example › java-utility-method › array-intersect-index-0.html
Java Utililty Methods Array Intersect
List of utility methods to do Array Intersect · HOME · Java · A · Array Intersect · The list of methods to do Array Intersect are organized into topic(s). « · 1 · 2 ·
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › intersection-of-two-arrays
Intersection of two Arrays - GeeksforGeeks
Given two arrays a[] and b[], find their intersection — the unique elements that appear in both.
Published: July 27, 2025
🌐
Enjoy Algorithms
enjoyalgorithms.com › blog › intersection-of-unsorted-arrays
Find Intersection of Two Arrays
Suppose m > n and the elements in both arrays are distinct. The intersection represents a list of common elements present in both arrays.
Top answer
1 of 4
8

Algorithm

You're using a O(n log(n)) algorithm here, which could be O(n²) for difficult cases since contains() is O(n) and is called in a loop. Instead, use the property of HashSet: access is O(1), which means you can achieve this in O(n) time. My algorithm below simply keeps track of what it can add to the result. I can add everything that exists in the first list, but I should not add an item I already added.

See my tested code for my implementation:

public static List<Integer> intersection(List<Integer> a, List<Integer> b){
    Set<Integer> canAdd = new HashSet<Integer>(a);
    List<Integer> result = new ArrayList<Integer>();

    for (int n: b) {
        if(first.contains(n)) {
            result.add(n);
            // we wish to add only one n
            canAdd.remove(n);
        }
    }

    return result;
}

Comments on your code

  1. You should return a List, not an ArrayList since it's an implementation detail. Using an ArrayList is OK here since adding at the end of it has O(1) amortized complexity. Otherwise, lists should be LinkedList (when adding to the beginning, not to the end, as @Landei points out).
  2. Be careful about the names you choose. findIt doesn't seem to be appropriate, but removeDuplicates or intersection describes what the code does.
2 of 4
3

@Cygal : Assuming that HashSet.contains() is really faster than the List one, this could be the ultimate code :-)

public static List<Integer> intersection(List<Integer> a, List<Integer> b) {
    Set<Integer> aSet = new HashSet<Integer>(a);
    Set<Integer> bSet = new HashSet<Integer>(b);

    for(Iterator<Integer> it = aSet.iterator(); it.hasNext();) {
        if(!bSet.contains(it.next())) it.remove();
    }

    return new ArrayList<Integer>(aSet);
}
🌐
YouTube
youtube.com › watch
Find Intersection of Two Arrays - Java Code - YouTube
Write a java program to find intersection of two arrays. Write a java program to find common elements in two arrays.Given two sorted arrays, Write a java cod...
Published: April 28, 2018
🌐
YouTube
youtube.com › xavier elon
LeetCode 349 | Intersection of Two Arrays | Solution Explained (Java) - YouTube
Given two arrays, write a function to compute their intersection.Example 1:Input: nums1 = [1,2,2,1], nums2 = [2,2]Output: [2]Running Time: O(N+M)Space Comple
Published: October 15, 2020
Views: 5K
🌐
GitHub
gist.github.com › BiruLyu › f4ffc25dae7de3222148b44571335b1f
349. Intersection of Two Arrays(#).java · GitHub
349. Intersection of Two Arrays(1st).java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ·