We can remove duplicate elements in an array in two ways: –
- Using a temporary array
- Using a separate index.
Note – To remove the duplicate element from an array, the array must be in sorted order. If the array is not sorted, you can sort it by calling the Arrays. sort(arr) method.
Remove Duplicate Elements in an Array using Temporary Array
Example 1
public class A {
public static void main(String[] args) {
int arr[] = {1,1,2,3,4,4,5};
int len =arr.length;
int temp[] =new int[arr.length];
int j=0;
for(int i=0; i<len-1;i++) {
if(arr[i]!=arr[i+1]) {
temp[j]=arr[i];
j++;
}
}
temp[j]=arr[arr.length-1];
for(int m=0; m<=j; m++) {
System.out.println(temp[m]);
}
}
Output:
1
2
3
4
5
You Also Learn –
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- What is Exception Handling in Java
- Types of Exceptions in Java
- What is inheritance in Java
- What is the Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keywords in Java with Example
- What is Method In Java With Example
- What is Constructor in Java With Example
- What is Polymorphism in java
- What is a non-static variable in java
- Types of access specifiers in java
- What is the local variable in java
- Types of loops in java with program
Remove Duplicate Element in Array using a separate index
Example 1
public class A{
public static void main(String[] args) {
int arr[] = {1,1,2,3,4,4,5};
int len =arr.length;
int j=0;
for(int i=0; i<len-1;i++) {
if(arr[i]!=arr[i+1]) {
arr[j]=arr[i];
j++;
}
}
arr[j]=arr[arr.length-1];
for(int m=0; m<=j; m++) {
System.out.println(arr[m]);
}
}
Output:
1
2
3
4
5