A HashSet stores unique elements. You can use it to remove duplicate values from a collection by passing that collection to its constructor.
In this example, you will remove duplicate programming language names from a list.
Source code
Save the following code as RemoveDuplicatesExample.java:
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveDuplicatesExample {
void main() {
List<String> languages = List.of(
"Java", "Python", "Java", "Kotlin", "Python");
Set<String> uniqueLanguages = new HashSet<>(languages);
IO.println("Original list: " + languages);
IO.println("Original count: " + languages.size());
IO.println("Unique count: " + uniqueLanguages.size());
IO.println("Unique languages:");
uniqueLanguages.stream()
.sorted()
.forEach(IO::println);
}
}
Explanation
The original list contains five elements, including repeated values:
List<String> languages = List.of(
"Java", "Python", "Java", "Kotlin", "Python");
Both "Java" and "Python" appear twice.
Creating a set from the list
The following statement copies the list’s elements into a HashSet:
Set<String> uniqueLanguages = new HashSet<>(languages);
A set does not retain duplicate elements, so the resulting set contains three language names.
The original list remains unchanged.
The variable uses the interface type Set<String>, while HashSet provides the implementation.
How duplicates are identified
HashSet uses hashCode() and equals() to identify duplicate elements.
For strings, equality depends on their text and is case-sensitive. For example, "Java" and "java" are different values and would both remain in the set.
When storing objects from your own classes, implement equals() and hashCode() consistently so the set can recognize logically equal objects.
Displaying the unique values
A HashSet does not guarantee iteration order. The example sorts the elements before printing them to produce predictable output:
uniqueLanguages.stream()
.sorted()
.forEach(IO::println);
stream() creates a stream of the set’s elements. sorted() arranges the strings in their natural order, and forEach() prints each one.
Sorting the stream does not change the set.
Run the example
Compile and run the file:
javac RemoveDuplicatesExample.java
java RemoveDuplicatesExample
Output
Original list: [Java, Python, Java, Kotlin, Python]
Original count: 5
Unique count: 3
Unique languages:
Java
Kotlin
Python
Preserving insertion order
If you want to remove duplicates while preserving the order in which values first appeared, use a LinkedHashSet:
Set<String> uniqueLanguages = new LinkedHashSet<>(languages);
Import java.util.LinkedHashSet to use it. Iterating over this set produces Java, Python, and Kotlin, in that order.
