forked from anish2210/hacktober2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdublicatearraylist.java
51 lines (37 loc) · 1.07 KB
/
dublicatearraylist.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Java program to remove duplicates from ArrayList
import java.util.*;
public class dublicatearraylist {
// Function to remove duplicates from an ArrayList
public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list)
{
// Create a new LinkedHashSet
Set<T> set = new LinkedHashSet<>();
// Add the elements to set
set.addAll(list);
// Clear the list
list.clear();
// add the elements of set
// with no duplicates to the list
list.addAll(set);
// return the list
return list;
}
// Driver code
public static void main(String args[])
{
// Get the ArrayList with duplicate values
ArrayList<Integer>
list = new ArrayList<>(
Arrays
.asList(1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5));
// Print the Arraylist
System.out.println("ArrayList with duplicates: "
+ list);
// Remove duplicates
ArrayList<Integer>
newList = removeDuplicates(list);
// Print the ArrayList with duplicates removed
System.out.println("ArrayList with duplicates removed: "
+ newList);
}
}