1. Introduction
LinkedList in Java does not automatically handle duplicates. To remove duplicate elements, you can use a HashSet which does not allow duplicate values. You iterate through the LinkedList, add each element to the HashSet, and if the add() method returns false (indicating a duplicate value), you remove that element from the LinkedList.
2. Program Steps
1. Create a LinkedList and add some elements to it, including duplicates.
2. Create a HashSet.
3. Iterate over the LinkedList.
4. For each element, try to add it to the HashSet.
5. If the add() method returns false, remove the element from the LinkedList.
6. Print the LinkedList to verify that duplicates have been removed.
3. Code Program
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListRemoveDuplicates {
public static void main(String[] args) {
// Step 1: Create a LinkedList and add some elements including duplicates
LinkedList<String> listWithDuplicates = new LinkedList<>();
listWithDuplicates.add("Apple");
listWithDuplicates.add("Banana");
listWithDuplicates.add("Apple");
listWithDuplicates.add("Cherry");
listWithDuplicates.add("Banana");
// Step 2: Create a HashSet
HashSet<String> set = new HashSet<>();
// Step 3 and 4: Iterate over the LinkedList and add elements to HashSet
ListIterator<String> iterator = listWithDuplicates.listIterator();
while (iterator.hasNext()) {
String element = iterator.next();
// Step 5: If add() returns false, remove the element from the LinkedList
if (!set.add(element)) {
iterator.remove();
}
}
// Step 6: Print the LinkedList
System.out.println(listWithDuplicates);
}
}
Output:
[Apple, Banana, Cherry]
4. Step By Step Explanation
Step 1: A LinkedList named listWithDuplicates is created, and some elements, including duplicates, are added to it.
Step 2: A HashSet named set is created to keep track of unique elements in the LinkedList.
Step 3 and 4: We use a ListIterator to iterate over the LinkedList. For each element, we try to add it to the HashSet.
Step 5: If the add() method returns false, it indicates a duplicate, and we remove that element from the LinkedList using iterator.remove().
Step 6: Finally, the modified LinkedList is printed, and we can observe that the duplicates have been removed.