Below is a Java program to remove duplicates from an ArrayList:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class RemoveDuplicates {
public static void main(String[] args) {
// Create an ArrayList with duplicates
List<Integer> numbersWithDuplicates = new ArrayList<>();
numbersWithDuplicates.add(1);
numbersWithDuplicates.add(2);
numbersWithDuplicates.add(3);
numbersWithDuplicates.add(2);
numbersWithDuplicates.add(4);
numbersWithDuplicates.add(1);
numbersWithDuplicates.add(5);
System.out.println("ArrayList with duplicates: " + numbersWithDuplicates);
// Remove duplicates
List<Integer> numbersWithoutDuplicates = removeDuplicates(numbersWithDuplicates);
// Print ArrayList after removing duplicates
System.out.println("ArrayList after removing duplicates: " + numbersWithoutDuplicates);
}
public static <T> List<T> removeDuplicates(List<T> list) {
// Create a HashSet to store unique elements
HashSet<T> set = new HashSet<>();
// Create a new ArrayList to store elements without duplicates
List<T> newList = new ArrayList<>();
// Iterate over the original list
for (T element : list) {
// If element is not already in the HashSet, add it to the new list and set
if (set.add(element)) {
newList.add(element);
}
}
return newList;
}
}
Explanation:
- The `removeDuplicates()` method takes an ArrayList as input and returns a new ArrayList with duplicates removed.
- It uses a HashSet to store unique elements encountered in the ArrayList.
- Elements are iterated over one by one, and if they are not already present in the HashSet, they are added to both the HashSet and the new ArrayList.
- This ensures that only unique elements are added to the new ArrayList.
- Finally, the new ArrayList without duplicates is returned.