Junior — Middle
Are you considering using the HashMap data structure to optimize the process of removing duplicates in an unordered list?
sobes.tech AI
Answer from AI
Yes, using the HashMap data structure (in Java — HashMap) is an efficient way to eliminate duplicate elements in an unsorted list. HashMap provides fast access and key existence checks in amortized O(1) time, significantly speeding up the process compared to iterating over all elements.
Example approach:
- Create an empty HashMap or HashSet.
- Iterate over the list elements.
- For each element, check if it already exists in the HashMap/HashSet.
- If not, add it.
- In the end, obtain a collection of unique elements.
Example code in Java using HashSet:
import java.util.*;
public class RemoveDuplicates {
public static List<Integer> removeDuplicates(List<Integer> list) {
Set<Integer> set = new HashSet<>();
List<Integer> result = new ArrayList<>();
for (Integer item : list) {
if (set.add(item)) { // add returns false if the element already exists
result.add(item);
}
}
return result;
}
}
Thus, HashMap/HashSet allows efficient filtering of duplicate elements without the need for sorting or nested loops.