How to remove duplicate elements from array in Java

There are many ways of removing duplicate elements from Array in Java. Following are the mentioned ways :

1.Remove Duplicate Element in Array using Temporary Array

  • Remove duplicates when array elements are sorted
  • Remove duplicates when array elements are not sorted

2. Remove duplicates in array using LinkedHashSet

Remove Duplicate Element in Array using Temporary Array

Sometimes there is a situation in which you are not allowed to use any collections API then you can use following approaches based on the requirement.

  • Remove duplicates when array elements are sorted
  • Remove duplicates when array elements are not sorted

Lets understand these two methods one by one.

Remove duplicates when array elements are sorted

If elements of array are sorted then remove duplicates by using following steps:

  • Make a new arrayΒ 'tempArr'Β having same size as original arrayΒ 'orgArr'.
  • Iterate over array from index β€˜0’.
  • Compare current element with the next index element until the mismatch is found.
  • Add element toΒ 'tempArr'Β and make current element to the element which was previously mismatched.
  • Then continue the iteration till the end.
public class ArrayDupExample 
{
    public static void main(String[] args) throws Exception 
    {
        // Duplicate Elements in an Array
        Integer[] orgArr = new Integer[] { 1, 1, 2, 2, 3, 3, 4, 4, 6, 6,7, 7 };
 
        
        System.out.println(Arrays.toString(orgArr));
 
        Integer[] tempArray = removeDuplicateElements(orgArr);
 
        // Final Array
        System.out.println(Arrays.toString(tempArray));
    }
 
    private static Integer[] removeDuplicateElements(Integer[] orgArr) {
 
        Integer[] tempArr = new Integer[orgArr.length];
         
        int indexJ = 0;
        for (int indexI = 0; indexI < orgArr.length - 1; indexI++) 
        {
            Integer currentElement = orgArr[indexI];
             
            if (currentElement != orgArr[indexI+1]) {
            	tempArr[indexJ++] = currentElement;
            }
        }
         
        tempArr[indexJ++] = orgArr[orgArr.length-1];
         
        return tempArr;
    }
}
##Output
[1, 1, 2, 2, 3, 3, 4, 4, 6, 6, 7, 7]
[1, 2, 3, 4, 6, 7, null, null, null, null, null, null]

Remove duplicates when array elements are not sorted

If there is a unsorted array, then you have to sort it first using Arrays.sort(arr) method.

import java.util.Arrays;

public class ArrayDupExample {
	public static int removeDuplicateElements(int arr[], int n) {
		if (n == 0 || n == 1) {
			return n;
		}
		int[] temp = new int[n];
		int j = 0;
		for (int i = 0; i < n - 1; i++) {
			if (arr[i] != arr[i + 1]) {
				temp[j++] = arr[i];
			}
		}
		temp[j++] = arr[n - 1];
		// Changing the original array
		for (int i = 0; i < j; i++) {
			arr[i] = temp[i];
		}
		return j;
	}

	public static void main(String[] args) {
		
		// This is unsorted array
		int arr[] = { 10, 70, 30, 30, 25, 25, 30, 40, 71, 51 };
		
		// Sorting array first
		Arrays.sort(arr);
		
		int length = arr.length;
		length = removeDuplicateElements(arr, length);
		
		// printing elements of Array
		for (int i = 0; i < length; i++)
			System.out.print(arr[i] + " ");
	}
}
##Output
10 25 30 40 51 70 71

Remove duplicates in array using LinkedHashSet

As we know that Set implementation stores the unique elements in it. Therefore we can use the LinkedHashSet

If there is not any condition for not using any collections API thenΒ LinkedHashSetΒ is the best method for removing duplicate elements from an array. LinkedHashSet does below two actions internally :

  • Remove duplicate elements as Set stores unique elements in it.
  • And maintains the order of insertion of elements into it

Below is the java program to remove the duplicate elements from Array in Java using LinkedHashSet.

import java.util.Arrays;
import java.util.LinkedHashSet;

public class ArrayDupExample {

    public static void main(String[] args)  
    {
        //Array having duplicate elements
        Integer[] dup = new Integer[] {1,2,3,4,5,1,4,3,5};
         
        
        System.out.println( Arrays.toString(dup) );
         
        //Creating the Set from array of elements
        LinkedHashSet<Integer> linkedHashSetArr = new LinkedHashSet<Integer>( Arrays.asList(dup) );
         
        //Array without duplicates
        Integer[] numbersWithoutDuplicates = linkedHashSetArr.toArray(new Integer[] {});
         
        //Array Elements
        System.out.println( Arrays.toString(numbersWithoutDuplicates) );
    }
}
##Output
[1, 2, 3, 4, 5, 1, 4, 3, 5]
[1, 2, 3, 4, 5]

Conclusion

You have learned about various ways of removing duplicate elements of Array.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply