Convert array to Set<String>

new HashSet<String>(Arrays.asList(array));

and do

Set<String> commonOnes = biggerSet.retainAll(smallerSet);
biggerSet.removeAll(commonOnes).add(smallerSet.removeAll(commonOnes))

or use guava difference()

Answer from Jigar Joshi on Stack Overflow
Top answer
1 of 2
12

Convert array to Set<String>

new HashSet<String>(Arrays.asList(array));

and do

Set<String> commonOnes = biggerSet.retainAll(smallerSet);
biggerSet.removeAll(commonOnes).add(smallerSet.removeAll(commonOnes))

or use guava difference()

2 of 2
5

This runs in O(n log n + m log m), where n is the size of first, and m is the size of second. Basically, it sorts the arrays, then pass through each one, adding ones that don't match to the LinkedList at each opportunity, then makes an array at the end. The earlier revision of this code did not work correctly because the trailing elements in the longer list were not getting added at the end.

public class SetDifference {
    public static void main(String... args) {
        String[] arrA = {"1", "2", "3", "4", "5", "25", "10"};
        String[] arrB = {"1", "2", "10", "4", "30"};

        System.out.println(Arrays.toString(differences(arrA, arrB)));
    }

    public static String[] differences(String[] first, String[] second) {
        String[] sortedFirst = Arrays.copyOf(first, first.length); // O(n)
        String[] sortedSecond = Arrays.copyOf(second, second.length); // O(m)
        Arrays.sort(sortedFirst); // O(n log n)
        Arrays.sort(sortedSecond); // O(m log m)

        int firstIndex = 0;
        int secondIndex = 0;

        LinkedList<String> diffs = new LinkedList<String>();  

        while (firstIndex < sortedFirst.length && secondIndex < sortedSecond.length) { // O(n + m)
            int compare = (int) Math.signum(sortedFirst[firstIndex].compareTo(sortedSecond[secondIndex]));

            switch(compare) {
            case -1:
                diffs.add(sortedFirst[firstIndex]);
                firstIndex++;
                break;
            case 1:
                diffs.add(sortedSecond[secondIndex]);
                secondIndex++;
                break;
            default:
                firstIndex++;
                secondIndex++;
            }
        }

        if(firstIndex < sortedFirst.length) {
            append(diffs, sortedFirst, firstIndex);
        } else if (secondIndex < sortedSecond.length) {
            append(diffs, sortedSecond, secondIndex);
        }

        String[] strDups = new String[diffs.size()];

        return diffs.toArray(strDups);
    }

    private static void append(LinkedList<String> diffs, String[] sortedArray, int index) {
        while(index < sortedArray.length) {
            diffs.add(sortedArray[index]);
            index++;
        }
    }
}
🌐
GeeksforGeeks
geeksforgeeks.org › java › compare-two-arrays-java
Compare Two Arrays in Java - GeeksforGeeks
July 23, 2025 - Java provides a direct method Arrays.equals() to compare two arrays. There is a list of equals() methods in the Arrays class for different primitive types (int, char etc.) and one for Object type (which is the base of all classes in Java).
🌐
Baeldung
baeldung.com › home › java › java array › comparing arrays in java
Comparing Arrays in Java | Baeldung
January 8, 2024 - Having sorted the arrays in the same order first, we allow the deepEquals method to find if these two arrays are equal. Java 9 introduced a brand new method in the Arrays utility class called compare().
🌐
TutorialsPoint
tutorialspoint.com › how-to-compare-two-arrays-in-java
How to compare two arrays in Java
Following example uses equals method to check whether two arrays are or not. import java.util.Arrays; public class Main { public static void main(String[] args) throws Exception { int[] ary = {1,2,3,4,5,6}; int[] ary1 = {1,2,3,4,5,6}; int[] ary2 = {1,2,3,4}; System.out.println("Is array 1 equal to array 2??
Top answer
1 of 4
3

You can keep a count for each value in the first array. You can use a HashMap to hold how many occurences you have for a specific value.

Then, for each value in the second array, you can decrease the already calculated count for this value. In the end, if the count for a specific value is 0, this would mean that there were the same number of appearances in the both arrays. Otherwise, one of the arrays contained more occurences of value. The number of differences for a specific value would be abs(count[value]) (as it can get negative, in the case when the second arrays contains more occurences of value than the first array).

This Java code illustrates the approach:

public List<Integer> findDiff(int[] first, int[] second) {
  Map<Integer, Integer> count = new HashMap<>();
  for (int value : first) {
    int current = count.getOrDefault(value, 0);
    count.put(value, current + 1);
  }
  for (int value : second) {
    int current = count.getOrDefault(value, 0);
    count.put(value, current - 1);
  }
  List<Integer> result = new ArrayList<>();
  for (Map.Entry<Integer, Integer> entry : count.getEntrySet()) {
    int diff = entry.getValue();
    int times = Math.abs(diff);
    for (int i = 0; i < times; i++) {
      result.add(entry.getKey());
    }
  }
  return result;
}

Clearly, we have a linear complexity for both time and memory.

2 of 4
1

Almost certainly not an optimal solution, but as something you can hopefully work with:

private static <X> Collection<X> findDiff(final Collection<X> a, final Collection<X> b) {
    // Copy the Collections so you don't modify inputs
    // and so you can safely 'remove' from them.
    final List<X> aCopy = new ArrayList<>(a);
    final List<X> bCopy = new ArrayList<>(b);

    // Remove all common elements from the copies
    // Using 'removeAll' will pull out duplicates,
    // so do this one-by-one.
    for (final X bElement : b) {
        aCopy.remove(bElement);
    }
    // Note it's important to iterate over 'a' here, not
    // aCopy since the elements of aCopy (may) have had some
    // entries 'remove'd.
    for (final X aElement : a) {
        bCopy.remove(aElement);
    }

    // Combine the two cleared out lists to find
    // the cumulative difference.
    final List<X> diff = new ArrayList<>(aCopy);
    diff.addAll(bCopy);

    return Collections.unmodifiableCollection(diff);
}

Note, you can convert your int[] to a Collection<Integer> using something simple like:

IntStream.of(arr).boxed().collect(Collectors.toList());

Note also: you can do this with fewer intermediate Collections. You only need to copy one of the input ones if you don't mind modifying the inputs. And you don't need to combine the two into a new diff one. This was just something to work with (and more explanatory).

Find elsewhere
🌐
YouTube
youtube.com › api pothi
10 How to get the difference between two arrays - YouTube
#INTERVIEW,#DIFFERENCE,#ARRAYSSubscribe :https://www.youtube.com/channel/UCVbV-R2Az00kwqxh9gvH86w💌Email : infoapipothi@gmail.com*Facebook Page : https://www
Published: October 3, 2019
Views: 1K
🌐
YouTube
youtube.com › watch
How to Compare Arrays in Java - Comparing 2 Arrays by Example - Learn Java Programming - Appficial - YouTube
When comparing two arrays is Java, you cannot use the == operator to compare arrays because iIt will only tell you if the two arrays point to the same object...
Published: March 1, 2018
🌐
Medium
medium.com › @AlexanderObregon › javas-arrays-mismatch-method-explained-81e0cfe56a02
Java’s Arrays.mismatch() Method Explained | Medium
January 9, 2025 - The mismatch() method from the java.util.Arrays class is a utility for comparing two arrays and finding the index of the first differing…
🌐
DataCamp
datacamp.com › doc › java › compare
Java Array compare()
The Arrays.compare() method compares two arrays lexicographically. It returns 0 if the arrays are equal, a negative integer if the first array is lexicographically less, and a positive integer if the first array is lexicographically greater. This method can be used for arrays of various types ...
🌐
DEV Community
dev.to › aurban28 › arraysmismatch-and-arrayscompare-in-java-15ch
mismatch() and compare() in Java - DEV Community
November 30, 2024 - 2. Arrays.mismatch(T[] a, T[] b) The mismatch method finds the index of the first differing element between two arrays.
🌐
YouTube
youtube.com › shorts › fJ4ApnrD55o
How to compare two Arrays in Java #shorts #javainterviewquestions #javaprogramming - YouTube
How to compare two Arrays in Java #shorts #javainterviewquestions #javaprogramming
Published: March 19, 2023
🌐
LeetCode
leetcode.com › problems › find-the-difference-of-two-arrays
Find the Difference of Two Arrays - LeetCode
Find the Difference of Two Arrays - Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: * answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
🌐
Medium
medium.com › @AlexanderObregon › javas-arrays-compare-method-explained-7989daf18608
Java’s Arrays.compare() Method Explained | Medium
February 6, 2025 - If a difference is found at any position, the result depends on the first mismatched element — returning a positive or negative value based on which element is greater. For primitive arrays, compare() evaluates values using natural ordering. That means numbers are compared just like they would be in a regular numerical sort. ... import java.util.Arrays; public class ComparePrimitiveArrays { public static void main(String[] args) { int[] array1 = {5, 10, 15}; int[] array2 = {5, 10, 20}; int[] array3 = {5, 10, 15}; System.out.println(Arrays.compare(array1, array2)); // Output: -1 System.out.println(Arrays.compare(array1, array3)); // Output: 0 System.out.println(Arrays.compare(array2, array1)); // Output: 1 } }
🌐
Java67
java67.com › 2014 › 05 › how-to-compare-two-arrays-in-java-string-int-example.html
How to compare two Arrays in Java to check if they are equal - [String & Integer Array Example] | Java67
How to compare two Arrays in Java to check if they... How to Convert or Print Array to String in Java? E... How to implement PreOrder traversal of Binary Tree... How to reverse a singly linked list in Java withou... How to Reverse an Array in place in Java? Example ... 5 Differences between an array and linked list in ...