← Back to Core Java Course | Chapter 11: Collections | Lesson 11 of 17

Java HashSet

A HashSet is a bag of unique items with no repeats, like a collection of different stickers. Adding a duplicate does nothing.
Syntax
java
HashSet<Type> set = new HashSet<>();
set.add(item);
set.contains(item);
set.remove(item);

Introduction to HashSet

HashSet stores a collection of unique elements backed internally by a HashMap, silently discarding any element you try to add that's already present according to equals().

Example: Introduction to HashSet

java
import java.util.HashSet;
public class Main {
	public static void main(String[] args) {
		HashSet<String> set = new HashSet<>();
		set.add("apple");
		set.add("apple"); // silently discarded
		System.out.println(set.size());
	}
}

Removing and Searching Elements

remove(element) deletes a matching element if present, and contains(element) checks membership — both run in average O(1) time thanks to the same hashing HashSet inherits from HashMap.

Example: Removing and Searching Elements

java
// Import java.util.HashSet so it can be used by its short name
import java.util.HashSet;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new HashSet object and store it in set
		HashSet<String> set = new HashSet<>();
		set.add("apple");
		// Print a line to the console
		System.out.println(set.contains("apple"));
		set.remove("apple");
		// Print a line to the console
		System.out.println(set.contains("apple"));
	}
}

Iterating over HashSet

Iterating a HashSet visits every unique element exactly once, but like HashMap, it gives no guarantee about the order elements come back in — don't rely on insertion order or any particular sequence.

Example: Iterating over HashSet

java
import java.util.HashSet;
public class Main {
	public static void main(String[] args) {
		HashSet<String> set = new HashSet<>();
		set.add("apple");
		set.add("banana");
		for (String item : set) { // order not guaranteed
			System.out.println(item);
		}
	}
}

Set Operations

HashSet supports mathematical set operations through its collection methods: addAll() for union, retainAll() for intersection, and removeAll() for difference between two sets.

Example: Set Operations

java
// Import java.util.HashSet so it can be used by its short name
import java.util.HashSet;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new HashSet object and store it in a
		HashSet<Integer> a = new HashSet<>(java.util.List.of(1, 2, 3));
		// Create a new HashSet object and store it in b
		HashSet<Integer> b = new HashSet<>(java.util.List.of(2, 3, 4));
		HashSet<Integer> intersection = new HashSet<>(a);
		intersection.retainAll(b);
		// Print a line to the console
		System.out.println(intersection);
	}
}

Converting HashSet to List

Converting a HashSet to a List (via new ArrayList<>(mySet)) is useful when you need indexed access or a defined order after using the set purely for its fast uniqueness guarantee.

Example: Converting HashSet to List

java
import java.util.HashSet;
import java.util.ArrayList;
public class Main {
	public static void main(String[] args) {
		HashSet<String> set = new HashSet<>();
		set.add("apple");
		set.add("banana");
		ArrayList<String> list = new ArrayList<>(set); // now has indexed access
		System.out.println(list.get(0));
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting an order when iterating, since HashSet has none.
  2. Expecting duplicates, which are ignored.
  3. Using objects without equals() and hashCode(), so equal objects are stored twice.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.