remove duplicates from a sorted array java code example
Example 1: java remove duplicates
import java.util.*;
public class RemoveDuplicatesFromArrayList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,2,2,3,5);
System.out.println(numbers);
Set<Integer> hashSet = new LinkedHashSet(numbers);
ArrayList<Integer> removedDuplicates = new ArrayList(hashSet);
System.out.println(removedDuplicates);
}
}
Example 2: how to remove duplicates from an array java
public class RemoveDuplicateInArrayExample{
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];
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
public static void main (String[] args) {
int arr[] = {10,20,20,30,30,40,50,50};
int length = arr.length;
length = removeDuplicateElements(arr, length);
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}