Junior — Middle
Do you plan to use HashSet data structure to optimize the process of removing duplicates in an unordered list?
sobes.tech AI
Answer from AI
Yes, using HashSet is an efficient way to eliminate duplicates in an unordered list. HashSet stores only unique elements, and when adding, it checks for the presence of an element in constant time on average.
Example in Java:
import java.util.*;
public class RemoveDuplicates {
public static List<Integer> removeDuplicates(List<Integer> list) {
return new ArrayList<>(new HashSet<>(list));
}
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
List<Integer> unique = removeDuplicates(numbers);
System.out.println(unique); // Will output unique elements, order may not be preserved
}
}
If order is important, you can use LinkedHashSet, which preserves insertion order.