Java Sets: HashSet, LinkedHashSet and TreeSet
A guest list refuses the second Asha and add returns false. The same five arrivals print in three orders: HashSet scatters, LinkedHashSet remembers arrival, TreeSet sorts. Then a signup list with Neha twice becomes a set with her once, order kept.
What you will learn
- Use a Set to keep each value once and read add's true or false
- Explain how hashCode and equals let a set spot a repeat
- Predict the order of a HashSet, a LinkedHashSet and a TreeSet
- Remove repeats from a list while keeping its order
Before you start
- Java equals and hashCode
- From arrays to collections: the framework map
Sometimes you need only unique values. You could use a list and write your own logic to remove duplicates, but that's tedious. A set simply doesn't allow them.
A guest list, each name once
package org.studyeasy.s04l08;
import java.util.HashSet;
import java.util.Set;
public class Ex01_GuestList {
public static void main(String[] args) {
Set<String> guests = new HashSet<>();
guests.add("Asha");
guests.add("Ravi");
boolean addedAgain = guests.add("Asha"); // already on the list
System.out.println("Added again: " + addedAgain);
System.out.println("Size: " + guests.size());
System.out.println("Has Ravi: " + guests.contains("Ravi"));
}
}
Added again: false
Size: 2
Has Ravi: true
add returns a boolean. Asha is already there, so the second add gives false and nothing changes. Size stays 2, and contains confirms Ravi is in.
How does the set know? It uses the hashCode and equals pair: first the hash code, then equals. A name that isn't there is stored and add returns true; a name that is there is left alone and add returns false. String and wrappers like Integer already have both methods written, so there's nothing to implement.
Same names, three orders
package org.studyeasy.s04l08;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
public class Ex02_ThreeSets {
public static void main(String[] args) {
Set<String> hash = new HashSet<>();
Set<String> linked = new LinkedHashSet<>();
Set<String> tree = new TreeSet<>();
String[] arrivals = {"Neha", "Asha", "Ravi", "Neha", "Priya"};
for (String name : arrivals) { // same names, same order
hash.add(name);
linked.add(name);
tree.add(name);
}
System.out.println("HashSet: " + hash);
System.out.println("LinkedHashSet: " + linked);
System.out.println("TreeSet: " + tree);
}
}
HashSet: [Priya, Neha, Asha, Ravi]
LinkedHashSet: [Neha, Asha, Ravi, Priya]
TreeSet: [Asha, Neha, Priya, Ravi]
Neha arrives twice, so every set keeps her once and all three hold four names. Only the order differs.
- The HashSet puts each name in a bucket picked by its hash code and prints bucket by bucket. That order is Java's choice and comes with no promise; don't rely on it.
- The LinkedHashSet uses the same buckets but also keeps a thread through the names in the order they arrived, and prints by following it.
- The TreeSet builds a sorted tree. Neha is the root, Asha goes left, Ravi right, and Priya sits between Neha and Ravi. Read left to right, it's alphabetical.
One trap: tree.add(null) throws a NullPointerException. A TreeSet compares every value, and it can't compare null with a name.
Drop the repeat, keep the order
List<String> signups = new ArrayList<>();
signups.add("Neha");
signups.add("Asha");
signups.add("Neha"); // signed up twice
signups.add("Priya");
// the repeat drops out, the order stays
Set<String> unique = new LinkedHashSet<>(signups);
System.out.println("List: " + signups);
System.out.println("Set: " + unique);
List: [Neha, Asha, Neha, Priya]
Set: [Neha, Asha, Priya]
A list happily keeps both Nehas. Passing it into a new LinkedHashSet drops the second one, and the order stays, so four entries become three. A set has no index, though: unique.get(0) is "cannot find symbol".
Which set for which job
| HashSet | LinkedHashSet | TreeSet | |
|---|---|---|---|
| Repeats | refused | refused | refused |
| Order | no promise | arrival order | sorted |
| Speed | fastest | close behind | a little slower (keeps sorting) |
| Pick it when | order doesn't matter | order must stay | output must be sorted |
Default to HashSet. To sort by something other than alphabetical order, you need a comparator: see Comparable and Comparator.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java equals and hashCode: Why a HashSet Needs Both
== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.
From Arrays to Collections: The Java Collections Framework Map
An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.
Java Wrapper Classes and Autoboxing
List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.
Java ArrayList: The Stretchy Array
add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.
