Write a Java Program to remove duplicates in an ArrayList.
Certainly! Below is a simple Java program that demonstrates how to remove duplicates from an ArrayList
. This program uses a HashSet
to filter out duplicates since a HashSet
does not allow duplicate values.
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 some duplicate values
List<String> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add("Apple");
listWithDuplicates.add("Banana");
listWithDuplicates.add("Apple");
listWithDuplicates.add("Orange");
listWithDuplicates.add("Banana");
listWithDuplicates.add("Grapes");
System.out.println("Original List: " + listWithDuplicates);
// Remove duplicates
List<String> listWithoutDuplicates = removeDuplicates(listWithDuplicates);
System.out.println("List after removing duplicates: " + listWithoutDuplicates);
}
public static List<String> removeDuplicates(List<String> list) {
// Use a HashSet to remove duplicates
HashSet<String> set = new HashSet<>(list);
// Convert the HashSet back to an ArrayList
return new ArrayList<>(set);
}
}
ArrayList
, HashSet
, and List
from the java.util
package.ArrayList
called listWithDuplicates
and populate it with some strings, including duplicates.removeDuplicates
method, which takes the original list as an argument.removeDuplicates
method, we create a HashSet
from the list. This automatically removes any duplicate entries.HashSet
back to an ArrayList
and return it.When you run the program, you should see output similar to the following:
Original List: [Apple, Banana, Apple, Orange, Banana, Grapes]
List after removing duplicates: [Apple, Banana, Orange, Grapes]
Note that the order of elements in the resulting list may vary because HashSet
does not maintain the order of elements. If you need to maintain the original order, you can use a LinkedHashSet
instead of a HashSet
.