Loading

Quipoin Menu

Learn • Practice • Grow

data-structure-with-java / HashSet in Java
tutorial

HashSet in Java

HashSet is a collection that contains only unique elements. It's backed by a HashMap internally (elements are keys of a HashMap with a dummy value). Like HashMap, it offers O(1) average time for add, remove, and contains.

Basic operations:


Set set = new HashSet<>();
// Add
set.add("apple");
set.add("banana");
set.add("apple"); // duplicate ignored
// Check existence
boolean hasApple = set.contains("apple"); // true
// Remove
set.remove("banana");
// Size
int size = set.size(); // 1
// Iterate
for (String s : set) {
System.out.println(s);
}

Common use cases:
  • Removing duplicates from a list.
  • Membership testing (fast contains).
  • Set operations (union, intersection, difference).
Two Minute Drill
  • HashSet stores unique elements, backed by HashMap.
  • O(1) average time for add, remove, contains.
  • No duplicate elements; order not guaranteed.
  • Use LinkedHashSet for insertion order.
  • Use TreeSet for sorted order.

Need more clarification?

Drop us an email at career@quipoinfotech.com