Junior — Middle
How can you eliminate duplicate elements in an unsorted list by using HashSet or HashMap data structures for automatic removal through unique keys?
sobes.tech AI
Answer from AI
To remove duplicate elements from an unsorted list using HashSet or HashMap data structures in Java, you can leverage their property of storing unique keys.
- HashSet stores only unique elements. When duplicates are added, they are automatically ignored.
- HashMap can be used if you need to store key-value pairs where keys are unique.
Example of removing duplicates from a list using HashSet:
import java.util.*;
List<String> listWithDuplicates = Arrays.asList("apple", "banana", "apple", "orange", "banana");
// Create a HashSet from the list — duplicates will be removed automatically
Set<String> set = new HashSet<>(listWithDuplicates);
// If you need a list without duplicates
List<String> listWithoutDuplicates = new ArrayList<>(set);
System.out.println(listWithoutDuplicates);
If you want to preserve the order of elements, you can use LinkedHashSet:
Set<String> linkedHashSet = new LinkedHashSet<>(listWithDuplicates);
List<String> listOrdered = new ArrayList<>(linkedHashSet);
Thus, HashSet and HashMap allow efficient removal of duplicates by storing unique keys.