Syntax
HashSet<Type> set = new HashSet<>();Examples
Creating a HashSet and Adding Elements
Duplicates are automatically ignored.
import java.util.HashSet;
HashSet<String> tags = new HashSet<>();
tags.add("java");
tags.add("python");
tags.add("java"); // duplicate - ignored
System.out.println(tags); // [java, python] (order not guaranteed)
System.out.println(tags.size()); // 2Checking Membership
HashSet provides very fast membership testing, much faster than searching a List.
import java.util.HashSet;
HashSet<Integer> validIds = new HashSet<>();
validIds.add(101);
validIds.add(102);
validIds.add(103);
System.out.println(validIds.contains(102)); // true
System.out.println(validIds.contains(999)); // falseSet Operations
Union, intersection, and difference using retainAll, addAll, and removeAll.
import java.util.HashSet;
HashSet<Integer> a = new HashSet<>(java.util.List.of(1, 2, 3, 4));
HashSet<Integer> b = new HashSet<>(java.util.List.of(3, 4, 5, 6));
HashSet<Integer> union = new HashSet<>(a);
union.addAll(b);
System.out.println(union); // [1, 2, 3, 4, 5, 6]
HashSet<Integer> intersection = new HashSet<>(a);
intersection.retainAll(b);
System.out.println(intersection); // [3, 4]
HashSet<Integer> difference = new HashSet<>(a);
difference.removeAll(b);
System.out.println(difference); // [1, 2]Removing Duplicates from a List
A very common practical use of HashSet.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
List<String> namesWithDupes = new ArrayList<>(List.of("Fola", "Zain", "Fola", "Jamal"));
HashSet<String> uniqueNames = new HashSet<>(namesWithDupes);
System.out.println(uniqueNames); // [Fola, Zain, Jamal] (order not guaranteed)Best practices
- Use HashSet when you need fast membership testing (contains()) or automatic deduplication and do not care about element order
- Choose LinkedHashSet if you need deduplication while preserving insertion order, or TreeSet if you need elements kept sorted
- Always override equals() and hashCode() properly on any custom class stored in a HashSet, or duplicate detection will not work correctly
- Prefer a HashSet over an ArrayList for repeated contains() checks on large collections - it is dramatically faster
At a glance
- Purpose
- General-purpose application development
- File extension
- .java
- Runs in
- Java Virtual Machine
- Usually used with
- JDK and Java libraries
Specifications & further reading
Related Java documentation
ArrayList
ArrayList is a resizable array implementation of the List interface, part of java.util. Unlike a plain array, an ArrayList automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and iterating. Since generics require object types, an ArrayList of primitives (like int) actually stores their wrapper class (Integer) via autoboxing.LinkedList
LinkedList is a doubly-linked list implementation of both the List and Deque interfaces. Unlike ArrayList, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning or middle much faster, at the cost of slower random access by index. Because it implements Deque, LinkedList can also be used directly as a stack or queue.HashMap
HashMap stores data as key-value pairs, offering constant-time (average case) lookup, insertion, and deletion by key, backed by a hash table. Keys must be unique - adding a value with an existing key overwrites the previous value. HashMap does not guarantee any particular ordering of its entries, unlike LinkedHashMap (which preserves insertion order) or TreeMap (which keeps keys sorted).TreeMap & TreeSet
TreeMap and TreeSet are sorted collections backed by a red-black tree, automatically keeping their keys (or elements) in ascending order at all times. This ordering comes at a cost - operations run in logarithmic time rather than the constant time of HashMap/HashSet - but it's invaluable when you need sorted iteration, range queries, or to quickly find the smallest or largest element.
ArrayList is a resizable array implementation of the List interface, part of java.util. Unlike a plain array, an ArrayList automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and iterating. Since generics require object types, an ArrayList of primitives (like int) actually stores their wrapper class (Integer) via autoboxing.LinkedList
LinkedList is a doubly-linked list implementation of both the List and Deque interfaces. Unlike ArrayList, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning or middle much faster, at the cost of slower random access by index. Because it implements Deque, LinkedList can also be used directly as a stack or queue.HashMap
HashMap stores data as key-value pairs, offering constant-time (average case) lookup, insertion, and deletion by key, backed by a hash table. Keys must be unique - adding a value with an existing key overwrites the previous value. HashMap does not guarantee any particular ordering of its entries, unlike LinkedHashMap (which preserves insertion order) or TreeMap (which keeps keys sorted).TreeMap & TreeSet
TreeMap and TreeSet are sorted collections backed by a red-black tree, automatically keeping their keys (or elements) in ascending order at all times. This ordering comes at a cost - operations run in logarithmic time rather than the constant time of HashMap/HashSet - but it's invaluable when you need sorted iteration, range queries, or to quickly find the smallest or largest element.