HashSet
- Java course
- Beginner
- Lesson 69/116
- 4 min
Learn unique-element sets with HashSet.
Unique set: HashSet
When you want to drop duplicates automatically, you use a HashSet. If an element is already present when you add it again, the second add is a no-op; the set stays the same.
HashSet<String> tags = new HashSet<>();
tags.add("java");
tags.add("java");
tags.add("code");
// [java, code]Checking existence with contains is very fast; much faster than indexOf on a list. A set does not guarantee order; if order matters, prefer LinkedHashSet.
Looping over a set
You can walk a HashSet with a for-each loop. The output order of the elements may not match the insertion order, because HashSet makes no ordering promise.
for (String tag : tags) {
System.out.println(tag);
}To compute the intersection or union of two sets, you use retainAll and addAll. They let you do set operations in a single line.
Practice Collect unique tags
Create a HashSet<String>, add "java", "code", "java" and "maven". Then print the size of the set.
Starter code
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// Create a HashSet<String>
// Add four tags with add (java twice)
// Print the size with size()
}
}Sample solution
HashSet<String> tags = new HashSet<>();
tags.add("java");
tags.add("code");
tags.add("java");
tags.add("maven");
System.out.println(tags.size());Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match scenario to collection
| Term | Meaning |
|---|---|
Ordered, indexed list |
ArrayList |
Key-value table |
HashMap |
Unique element set |
HashSet |
Ordered unique set |
LinkedHashSet |
2 Fill in the blank: is it in the set?
HashSet<String> tags = new HashSet<>();
tags.add("java");
boolean has = tags.____("java");
HashSet<String> tags = new HashSet<>();
tags.add("java");
boolean has = tags.contains("java");
Explanation: contains("java") returns true.
3 What happens if you add the same element twice to a HashSet?
- Two copies are stored
- The second add is ignored; the set stays unchanged Correct answer
- It throws an error
- The old element is removed and the new one is added
Explanation: Set elements are unique; the second add is ignored.