0
0
JavaProgramBeginner · 2 min read

Java Program to Remove Duplicates from Array

To remove duplicates from an array in Java, you can use a LinkedHashSet to keep elements unique and preserve order, then convert it back to an array, like this: Set set = new LinkedHashSet<>(Arrays.asList(array)); Integer[] unique = set.toArray(new Integer[0]);.
📋

Examples

Input[1, 2, 2, 3, 4, 4, 5]
Output[1, 2, 3, 4, 5]
Input[10, 10, 10]
Output[10]
Input[]
Output[]
🧠

How to Think About It

To remove duplicates from an array, think of it like removing repeated items from a shopping list so each item appears only once. We can use a data structure that automatically ignores repeats, like a set, which only keeps unique items. Then, we convert this set back to an array to get the result without duplicates.
📐

Algorithm

1
Take the input array.
2
Create an empty set to store unique elements.
3
Add each element of the array to the set (duplicates are ignored).
4
Convert the set back to an array.
5
Return or print the new array without duplicates.
💻

Code

java
import java.util.*;

public class RemoveDuplicates {
    public static void main(String[] args) {
        Integer[] array = {1, 2, 2, 3, 4, 4, 5};
        Set<Integer> set = new LinkedHashSet<>(Arrays.asList(array));
        Integer[] unique = set.toArray(new Integer[0]);
        System.out.println(Arrays.toString(unique));
    }
}
Output
[1, 2, 3, 4, 5]
🔍

Dry Run

Let's trace the example array [1, 2, 2, 3, 4, 4, 5] through the code

1

Input array

[1, 2, 2, 3, 4, 4, 5]

2

Create LinkedHashSet and add elements

Set after adding elements: [1, 2, 3, 4, 5] (duplicates ignored)

3

Convert set back to array

Unique array: [1, 2, 3, 4, 5]

4

Print result

[1, 2, 3, 4, 5]

IterationElement AddedSet Content
11[1]
22[1, 2]
32[1, 2]
43[1, 2, 3]
54[1, 2, 3, 4]
64[1, 2, 3, 4]
75[1, 2, 3, 4, 5]
💡

Why This Works

Step 1: Using LinkedHashSet

A LinkedHashSet stores unique elements and keeps their original order, so duplicates are automatically removed.

Step 2: Converting array to list

We convert the array to a list with Arrays.asList() so we can pass it to the set constructor easily.

Step 3: Converting set back to array

After duplicates are removed, we convert the set back to an array using toArray(new Integer[0]) to get the final result.

🔄

Alternative Approaches

Using a boolean array for small integer ranges
java
import java.util.*;

public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 4, 4, 5};
        boolean[] seen = new boolean[100]; // assuming max value < 100
        List<Integer> uniqueList = new ArrayList<>();
        for (int num : array) {
            if (!seen[num]) {
                uniqueList.add(num);
                seen[num] = true;
            }
        }
        System.out.println(uniqueList);
    }
}
This method is fast but only works if array values are small non-negative integers.
Sorting and removing duplicates in-place
java
import java.util.*;

public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 4, 4, 5};
        Arrays.sort(array);
        int j = 0;
        for (int i = 1; i < array.length; i++) {
            if (array[i] != array[j]) {
                j++;
                array[j] = array[i];
            }
        }
        int[] unique = Arrays.copyOf(array, j + 1);
        System.out.println(Arrays.toString(unique));
    }
}
This method modifies the array and requires sorting, which changes element order.

Complexity: O(n) time, O(n) space

Time Complexity

Adding elements to a LinkedHashSet takes O(1) on average, so for n elements it is O(n).

Space Complexity

The set stores up to n unique elements, so space is O(n).

Which Approach is Fastest?

Using LinkedHashSet is usually fastest and simplest; sorting is slower due to O(n log n) time but uses less extra space.

ApproachTimeSpaceBest For
LinkedHashSetO(n)O(n)Preserving order, general use
Boolean arrayO(n)O(k)Small integer ranges, fast
Sorting + in-placeO(n log n)O(1)When order doesn't matter, space efficient
💡
Use a LinkedHashSet to remove duplicates while keeping the original order of elements.
⚠️
Trying to remove duplicates by comparing each element with every other element leads to slow, complex code.