1public static <T> List<T> removeDuplicates(List<T> list){
2 Set<T> set = new LinkedHashSet<>(list);
3 return new ArrayList<T>(set);
4}
1import java.util.*;
2
3public class RemoveDuplicatesFromArrayList {
4
5 public static void main(String[] args) {
6 List<Integer> numbers = Arrays.asList(1,2,2,2,3,5);
7
8 System.out.println(numbers);
9
10 Set<Integer> hashSet = new LinkedHashSet(numbers);
11 ArrayList<Integer> removedDuplicates = new ArrayList(hashSet);
12
13 System.out.println(removedDuplicates);
14 }
15}
16
1// Must sort arrays first --> Arrays.sort(arrayName)
2public class RemoveDuplicateInArrayExample{
3public static int removeDuplicateElements(int arr[], int n){
4 if (n==0 || n==1){
5 return n;
6 }
7 int[] temp = new int[n];
8 int j = 0;
9 for (int i=0; i<n-1; i++){
10 if (arr[i] != arr[i+1]){
11 temp[j++] = arr[i];
12 }
13 }
14 temp[j++] = arr[n-1];
15 // Changing original array
16 for (int i=0; i<j; i++){
17 arr[i] = temp[i];
18 }
19 return j;
20 }
21
22 public static void main (String[] args) {
23 int arr[] = {10,20,20,30,30,40,50,50};
24 int length = arr.length;
25 length = removeDuplicateElements(arr, length);
26 //printing array elements
27 for (int i=0; i<length; i++)
28 System.out.print(arr[i]+" ");
29 }
30}
1public class RemoveDuplicateElementDemo
2{
3 public static int removeDuplicate(int[] arrNumbers, int num)
4 {
5 if(num == 0 || num == 1)
6 {
7 return num;
8 }
9 int[] arrTemporary = new int[num];
10 int b = 0;
11 for(int a = 0; a < num - 1; a++)
12 {
13 if(arrNumbers[a] != arrNumbers[a + 1])
14 {
15 arrTemporary[b++] = arrNumbers[a];
16 }
17 }
18 arrTemporary[b++] = arrNumbers[num - 1];
19 for(int a = 0; a < b; a++)
20 {
21 arrNumbers[a] = arrTemporary[a];
22 }
23 return b;
24 }
25 public static void main(String[] args)
26 {
27 int[] arrInput = {1, 2, 3, 3, 4, 5, 5, 6, 7, 8};
28 int len = arrInput.length;
29 len = removeDuplicate(arrInput, len);
30 // printing elements
31 for(int a = 0; a < len; a++)
32 {
33 System.out.print(arrInput[a] + " ");
34 }
35 }
36}
1 ArrayList<Object> withDuplicateValues;
2 HashSet<Object> withUniqueValue = new HashSet<>(withDuplicateValues);
3
4 withDuplicateValues.clear();
5 withDuplicateValues.addAll(withUniqueValue);
1Set<String> set = new HashSet<>(yourList);
2yourList.clear();
3yourList.addAll(set);
4