Java HashSet

Learn about Java HashSet. Understand how to store unique elements, check for existence, and perform set operations.

A HashSet is a collection of items where every item is unique.

Think of a VIP Party List 🎟️.

  • You can't be on the list twice.
  • If you try to add "John" again, the bouncer says "He's already on the list!" and ignores you.
  • The order doesn't matter; you're either on the list or you're not.

Creating a HashSet

import java.util.HashSet;

HashSet<String> cars = new HashSet<String>();

Common Operations

1. Add Items

cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW"); // Duplicate! Will be ignored.
cars.add("Mazda");

System.out.println(cars);
// Output: [Volvo, Mazda, Ford, BMW] (Order is not guaranteed!)

2. Check if Item Exists

System.out.println(cars.contains("Mazda")); // Output: true

3. Remove Items

cars.remove("Volvo");
cars.clear(); // Removes ALL items

4. Set Size

System.out.println(cars.size());

Loop Through a HashSet

for (String i : cars) {
  System.out.println(i);
}

Tip 💡: HashSet is super fast for checking if something exists (contains()). It's much faster than ArrayList for this!

Did you know? 🧐 Internally, a HashSet uses a HashMap to store its elements! The elements you add are stored as keys in the map, and a dummy object is used as the value.

What is the main feature of a HashSet?


Note : Java is a statically-typed language. It means that all variables must be declared before they can be used.

Challenge

Complete this chapter to unlock the next one.

Challenge

Task:

Create a HashSet of Integers. Add 1, 2, and 1 again. Print the size.