How to remove duplicate elements of an array in java?
Answers
import java.util.Arrays;
public class RemoveDuplicateInArrayExample3{
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
Answer:
Explanation:
1. Remove duplicates in array using LinkedHashSet
If there is no pre-condition to not to use collections API then LinkedHashSet is the best approach for removing duplicate elements in an array. LinkedHashSet does two things internally :
Remove duplicate elements
Maintain the order of elements added to it
Java program to remove duplicates in array using LinkedHashSet. In given example, numbers is an integer array which has duplicate numbers 1, 3 and 5. We add all elements to LinkedHashSet, and then get back the content in array. The result array does not have duplicate integers.
ArrayExample.java
import java.util.Arrays;
import java.util.LinkedHashSet;
public class ArrayExample
{
public static void main(String[] args) throws CloneNotSupportedException
{
//Array with duplicate elements
Integer[] numbers = new Integer[] {1,2,3,4,5,1,3,5};
//This array has duplicate elements
System.out.println( Arrays.toString(numbers) );
//Create set from array elements
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>( Arrays.asList(numbers) );
//Get back the array without duplicates
Integer[] numbersWithoutDuplicates = linkedHashSet.toArray(new Integer[] {});
//Verify the array content
System.out.println( Arrays.toString(numbersWithoutDuplicates) );
}
}
Program Output.
Console
[1, 2, 3, 4, 5, 1, 3, 5]
[1, 2, 3, 4, 5]