Codectionary / Developer documentation / Java

HashSet

HashSet is a collection that stores unique elements with no guaranteed ordering, backed by a HashMap internally. Adding a duplicate element has no effect, since HashSet automatically enforces uniqueness. It provides constant-time (average case) performance for adding, removing, and checking membership, making it ideal for deduplication and fast lookups.

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()); // 2

Checking 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));  // false

Set 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("John", "Zain", "John", "Jamal"));

HashSet<String> uniqueNames = new HashSet<>(namesWithDupes);
System.out.println(uniqueNames);  // [John, 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

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading