Stop 08 · Collections & GenericsTopics · 5/10

HashSet & TreeSet

Part of the Java Roadmap

In short

Unique users who logged in today, distinct PIN codes in your orders, tags on a blog post: whenever the question is "which different things are there?", a Set is the answer.

Sets store unique elements. HashSet is fast and unordered, TreeSet keeps elements sorted, and LinkedHashSet preserves insertion order. Uniqueness depends on equals() and hashCode().

The jaadu stands at a decorated wedding gate stamping guests' hands and waving away a guest who already has a stamp.

Think of it like this

The wedding guest stamp

At a big Indian wedding, the person at the gate stamps each guest's hand. If someone already has a stamp, they are not counted again. HashSet is that gate: quick and unordered. TreeSet is the same gate, but it also keeps the guest list neatly in alphabetical order.

Watch it happen

Adding sign-ups to a HashSet

Riya
0
Arjun
1
Riya
2
Zoya
3
Arjun
4

1/5Five sign-ups arrive, but some people signed up twice.

The big ideas

What you need to know

HashSet: fast, no order

Backed by a HashMap, so add, remove and contains are O(1) on average. Iteration order is not guaranteed.

TreeSet: always sorted

Elements stay sorted, with first(), last(), floor() and ceiling(). Operations are O(log n).

LinkedHashSet: arrival order

Unique like HashSet but remembers insertion order. Handy for removing duplicates while keeping order.

Uniqueness needs equals

Hash sets use equals() and hashCode(). TreeSet uses compareTo or a Comparator instead.

See it in code

Walk through the code

java
1import java.util.*;2 3public class SetDemo {4    record Student(String name, int roll) {}5 6    public static void main(String[] args) {7        List<String> signups = List.of("Riya", "Arjun", "Riya", "Zoya", "Arjun");8 9        Set<String> fast = new HashSet<>(signups);10        Set<String> sorted = new TreeSet<>(signups);11        Set<String> inOrder = new LinkedHashSet<>(signups);12 13        System.out.println(fast.size()); // 314        System.out.println(sorted);      // [Arjun, Riya, Zoya]15        System.out.println(inOrder);     // [Riya, Arjun, Zoya]16 17        Set<Student> students = new HashSet<>();18        students.add(new Student("Riya", 12));19        boolean added = students.add(new Student("Riya", 12));20        System.out.println(added);       // false: records have equals and hashCode21    }22}

1/4The HashSet drops duplicates. Only 3 names remain.

Three sets built from the same list, each with a different order, plus proof that records work well as set elements.

Save yourself the pain

Common mistakes

Oops

Adding objects of your own class to a HashSet without equals() and hashCode().

Do this instead

Override both, or use a record. Otherwise two identical students both get stored.

Oops

Relying on the printed order of a HashSet.

Do this instead

It can change between runs or Java versions. Use TreeSet or LinkedHashSet when order matters.

Oops

Converting a list to a set and back just to check one item exists.

Do this instead

Build the set once and keep it. Repeated contains() on a set is what makes it fast.

Your mission

Distinct PIN codes

~20 min

Quick check

What does set.add(x) return when x is already in the set?

Go deeper

  1. 1Remove duplicates from a list using a HashSet.
  2. 2Use a TreeSet to keep a sorted set of names.
  3. 3Find the intersection of two sets with retainAll().

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge