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

Java HashSet

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;
public class Main {
	public static void main(String[] args) {
		HashSet<String> set = new HashSet<>();
		set.add("apple");
		System.out.println(set.contains("apple"));
		set.remove("apple");
		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;
public class Main {
	public static void main(String[] args) {
		HashSet<Integer> a = new HashSet<>(java.util.List.of(1, 2, 3));
		HashSet<Integer> b = new HashSet<>(java.util.List.of(2, 3, 4));
		HashSet<Integer> intersection = new HashSet<>(a);
		intersection.retainAll(b);
		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));
	}
}

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.