HashSet
Store unique elements with HashSet and perform fast membership tests and set operations.
Overview
Key Points
- •Import java.util.HashSet and java.util.Set
- •add(element) returns false if already present (no duplicate added)
- •contains(element) checks membership in O(1)
- •remove(element) deletes one element
- •No get(index) method because sets have no positional access
- •Iteration order is not guaranteed with HashSet
- •Set operations: addAll (union), retainAll (intersection), removeAll (difference)
- •Use Set<E> as the declared type for flexibility
Examples
Basic HashSet operations
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> colours = new HashSet<>();
colours.add("Red");
colours.add("Green");
colours.add("Blue");
colours.add("Red"); // duplicate, ignored
System.out.println(colours); // [Red, Green, Blue] (order may vary)
System.out.println("Size: " + colours.size()); // 3 (not 4)
System.out.println("Has Green: " + colours.contains("Green")); // true
colours.remove("Green");
System.out.println(colours);
}
}add returns false for duplicates. The set size stays 3 even after adding "Red" twice.
Deduplication of a list
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedHashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(
List.of("Alice","Bob","Alice","Carol","Bob","Alice")
);
System.out.println("Before: " + names);
// Quick dedup (order NOT preserved)
Set<String> deduped = new HashSet<>(names);
System.out.println("HashSet: " + deduped);
// Dedup preserving insertion order
Set<String> ordered = new LinkedHashSet<>(names);
System.out.println("LinkedHashSet: " + ordered);
}
}Passing a collection to the HashSet constructor deduplicates instantly. Use LinkedHashSet when you need the first-seen order preserved.
Set operations: union, intersection, difference
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Integer> a = new HashSet<>(Set.of(1, 2, 3, 4, 5));
Set<Integer> b = new HashSet<>(Set.of(4, 5, 6, 7, 8));
// Union
Set<Integer> union = new HashSet<>(a);
union.addAll(b);
System.out.println("Union: " + union);
// Intersection
Set<Integer> intersection = new HashSet<>(a);
intersection.retainAll(b);
System.out.println("Intersection: " + intersection); // [4, 5]
// Difference (a minus b)
Set<Integer> difference = new HashSet<>(a);
difference.removeAll(b);
System.out.println("Difference: " + difference); // [1, 2, 3]
}
}addAll, retainAll, and removeAll mutate the receiver set. Always work on a copy (new HashSet<>(a)) to keep the original.
Common Mistakes
- Expecting a specific iteration order from HashSet. The order depends on hash codes and can change across JVM runs
- Using a mutable object as a HashSet element and then mutating it. If hashCode changes, the set can no longer find the element
- Calling get(index) which does not exist on Set. Iterate instead
Note
To check if two lists share any common element, dump one into a HashSet and then call set.stream().anyMatch(other::contains). This is O(n+m) instead of O(n*m) for nested loops.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 4 exercises
Knowledge Check
Question 1 of 4