Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 04 / Topic 8 of 10

HashSet<T>: a ready-made "no duplicates allowed" collection

A set stores values with no duplicates, and answers "is this already in here?" fast. HashSet<T> is Java's ready-made, general-purpose set. Think of a guest list for Ravi's party: the same name on it twice is pointless — a set only cares whether a name is there, not how many times you tried to write it.

import java.util.HashSet;

class HashSetBasics {
    public static void main(String[] args) {
        HashSet<String> uniqueItems = new HashSet<>();
        System.out.println(uniqueItems.add("Rice")); // true: new item
        System.out.println(uniqueItems.add("Dal"));  // true: new item
        System.out.println(uniqueItems.add("Rice")); // false: already there, ignored

        System.out.println("Size: " + uniqueItems.size());
        System.out.println(uniqueItems.contains("Dal"));
        System.out.println(uniqueItems.contains("Milk"));

        System.out.println("--- items ---");
        for (String item : uniqueItems) {
            System.out.println(item);
        }

        uniqueItems.remove("Dal");
        System.out.println(uniqueItems);
    }
}

Output (examples/06_hash_set_basics.java):

true
true
false
Size: 2
true
false
--- items ---
Dal
Rice
[Rice]

add(...) returns a boolean: true means "this was new and got added," false means "this was already in the set, nothing changed." That return value is the whole trick behind "have I seen this before?" checks — no separate contains() call needed first. HashSet's iteration order has the exact same "not guaranteed" caveat as HashMap's (section 7): here it printed Dal, Rice, not insertion order, and that is allowed to differ on another JDK or with different data.

Full program: examples/06_hash_set_basics.java.

Done here? The practice set for Part 4 — including the solutions — is on the part page.

Search the guide