Skip to lesson

LinkedHashSet and TreeSet

LinkedHashSet is a set that remembers the order you added values in. TreeSet is a set that keeps its values sorted all the time and can answer questions like "what is the next value after 9:00?"

Three sets, three orders

All three classes follow the same Set rules: no duplicates, and the same add, contains, remove and size methods. What differs is the order in which you get the values back. The code below creates one of each.

Java
Set<String> a = new HashSet<>();         // any order, fastestSet<String> b = new LinkedHashSet<>();   // insertion orderSet<String> c = new TreeSet<>();         // sorted order
  • HashSet: no guaranteed order. The fastest: O(1) on average.
  • LinkedHashSet: the order in which values were first added. Almost as fast as HashSet.
  • TreeSet: sorted order, always. A little slower: O(log n) for add, contains and remove.
  • Pick by the question: "any order is fine" → HashSet, "keep my order" → LinkedHashSet, "keep it sorted" → TreeSet.
The same four values added as Mouse, Laptop, Adapter, Cable. HashSet prints Cable, Laptop, Mouse, Adapter. LinkedHashSet prints them as added. TreeSet prints Adapter, Cable, Laptop, Mouse.

Example 1 · The same cities in three sets

ThreeSetsDemo.javaJava
import java.util.HashSet;import java.util.LinkedHashSet;import java.util.Set;import java.util.TreeSet;
public class ThreeSetsDemo {    public static void main(String[] args) {        String[] trip = { "Mumbai", "Delhi", "Chennai", "Kolkata", "Delhi", "Pune" };
        Set<String> hash = new HashSet<>();        Set<String> linked = new LinkedHashSet<>();        Set<String> tree = new TreeSet<>();
        for (String city : trip) {            hash.add(city);            linked.add(city);            tree.add(city);        }
        System.out.println("HashSet:       " + hash);        System.out.println("LinkedHashSet: " + linked);        System.out.println("TreeSet:       " + tree);    }}
Output
HashSet:       [Delhi, Chennai, Kolkata, Pune, Mumbai]
LinkedHashSet: [Mumbai, Delhi, Chennai, Kolkata, Pune]
TreeSet:       [Chennai, Delhi, Kolkata, Mumbai, Pune]

What this code does

  • All three drop the second Delhi. Only the order differs: HashSet shows its internal order (not guaranteed), LinkedHashSet the trip order, TreeSet alphabetical order.
  • The variables are all of type Set<String>, so the rest of the code does not care which class is used.
For enum values there is also EnumSet, for example EnumSet.of(Day.MON, Day.WED). It is very fast and keeps the enum's declared order.

LinkedHashSet: your order, no duplicates

A LinkedHashSet is a HashSet that also remembers the order in which values were first added. It keeps the no-duplicates rule and prints in insertion order.

A LinkedHashSet is a HashSet with an extra chain that links the values in the order they were added. Loops and printing follow that chain, so the output is predictable. The example below keeps recent searches.

Example 2 · LinkedHashSet: recent searches without repeats

SearchHistoryDemo.javaJava
import java.util.LinkedHashSet;import java.util.Set;
public class SearchHistoryDemo {    public static void main(String[] args) {        String[] typed = { "java", "dsa", "java", "sql", "dsa", "react" };
        Set<String> history = new LinkedHashSet<>();        for (String query : typed) {            history.add(query);        }        System.out.println("History: " + history);
        history.remove("java");        history.add("java");        System.out.println("After searching java again: " + history);    }}
Output
History: [java, dsa, sql, react]
After searching java again: [dsa, sql, react, java]

What this code does

  • Each search appears once, at the place it was first typed. Adding java again in the loop did not move it.
  • To move a value to the end ("most recent"), remove it and add it again.

Adding a value that is already there does not move it; it keeps its first position. To move a value to the end, remove it and add it again. Like HashSet, it uses equals and hashCode.

A common use is removing duplicates while keeping the original order: new LinkedHashSet<>(list).

TreeSet: always sorted

A TreeSet is a Set that keeps its values sorted at all times, by natural order or by a Comparator. Its operations take O(log n), and it decides duplicates with compare, not equals.

A TreeSet keeps its values in a sorted tree: every add puts the value in its right place. The code below adds names, one of them twice.

SortedNames.javaJava
import java.util.*;
public class SortedNames {    public static void main(String[] args) {        Set<String> names = new TreeSet<>();        names.add("Meena");        names.add("Zoya");        names.add("aarav");        names.add("Meena");        System.out.println(names);        System.out.println(names.size());    }}
Output
[Meena, Zoya, aarav]
3

With 10 lakh values, a search takes only about 20 steps, which is what O(log n) means. The order comes from compareTo (the natural order from Comparable: numbers ascending, strings alphabetical) or from a Comparator you pass to the constructor: new TreeSet<>(comparator).

This has two big effects. First, a TreeSet decides duplicates with compareTo or compare, not with equals: if the comparison returns 0, the new value is treated as a duplicate and dropped. Second, it needs a way to compare: null throws NullPointerException, and a class that is not Comparable (with no comparator) throws ClassCastException on the first add.

String order compares character codes, so all capital letters come before small letters: "Zoya" sorts before "aarav".

Searching a sorted set

Because the values are sorted, a TreeSet can find neighbours of any value, even one that is not in the set. These methods belong to TreeSet (through the NavigableSet interface), so declare the variable as TreeSet<...>, not Set<...>. The code below tries a few.

Java
TreeSet<Integer> t = new TreeSet<>(List.of(10, 20, 30, 40));t.first();        // 10t.floor(25);      // 20t.ceiling(25);    // 30t.headSet(30);    // [10, 20]
  • first(), last(): smallest and largest. pollFirst(), pollLast() also remove them.
  • floor(x): largest value ≤ x. lower(x): largest value < x.
  • ceiling(x): smallest value ≥ x. higher(x): smallest value > x. All four return null if there is none.
  • headSet(x): values < x. tailSet(x): values ≥ x. subSet(a, b): from a up to but not including b. descendingSet(): reverse order.

Example 3 · TreeSet navigation: the next train

TrainTimesDemo.javaJava
import java.util.TreeSet;
public class TrainTimesDemo {    public static void main(String[] args) {        TreeSet<String> departures = new TreeSet<>();        departures.add("16:40");        departures.add("06:10");        departures.add("09:30");        departures.add("21:05");        departures.add("07:45");        departures.add("12:15");
        System.out.println("All trains: " + departures);        System.out.println("First: " + departures.first() + ", last: " + departures.last());
        String now = "09:00";        System.out.println("Next train after " + now + ": " + departures.ceiling(now));        System.out.println("Last train before " + now + ": " + departures.floor(now));        System.out.println("Train after 09:30: " + departures.higher("09:30"));        System.out.println("Train after 22:00: " + departures.ceiling("22:00"));
        System.out.println("Before noon: " + departures.headSet("12:00"));        System.out.println("From 16:00: " + departures.tailSet("16:00"));    }}
Output
All trains: [06:10, 07:45, 09:30, 12:15, 16:40, 21:05]
First: 06:10, last: 21:05
Next train after 09:00: 09:30
Last train before 09:00: 07:45
Train after 09:30: 12:15
Train after 22:00: null
Before noon: [06:10, 07:45, 09:30]
From 16:00: [16:40, 21:05]

What this code does

  • Times written as two-digit HH:MM strings sort correctly as text. 09:00 is not in the set, yet ceiling and floor find its neighbours.
  • ceiling("22:00") returns null because no train leaves that late. Always check for null before using the result.

Predict the output

Predict the TreeSet answer

Read the code and pick what it prints.

Round 1 of 2

What is printed?

TreeSet<Integer> prices = new TreeSet<>(List.of(10, 20, 30, 40));
System.out.println(prices.floor(25) + " " + prices.ceiling(25));

The comparator trap

Suppose a leaderboard uses a TreeSet that compares students only by marks. Aarav and Kabir both score 88. The comparator returns 0, so the set thinks Kabir is a duplicate of Aarav and quietly drops him.

Example 4 · Trap: a comparator on marks drops a student

DroppedStudentDemo.javaJava
import java.util.Comparator;import java.util.TreeSet;
record Student(String name, int marks) {    @Override    public String toString() {        return name + "(" + marks + ")";    }}
public class DroppedStudentDemo {    public static void main(String[] args) {        Comparator<Student> byMarks = (a, b) -> Integer.compare(a.marks(), b.marks());        TreeSet<Student> board = new TreeSet<>(byMarks);
        System.out.println(board.add(new Student("Aarav", 88)));        System.out.println(board.add(new Student("Diya", 92)));        System.out.println(board.add(new Student("Kabir", 88)));        System.out.println(board.add(new Student("Meera", 75)));
        System.out.println(board);        System.out.println("Students: " + board.size());    }}
Output
true
true
false
true
[Meera(75), Aarav(88), Diya(92)]
Students: 3

What this code does

  • Comparing Kabir with Aarav returns 0, so add returns false and Kabir is lost. No error, no warning.
  • The record's equals would say they are different, but a TreeSet never calls equals; only the comparator counts.

Example 5 · Fix: a tie-breaker, and a leaderboard

LeaderboardDemo.javaJava
import java.util.Comparator;import java.util.TreeSet;
record Student(String name, int marks) {    @Override    public String toString() {        return name + "(" + marks + ")";    }}
public class LeaderboardDemo {    public static void main(String[] args) {        Comparator<Student> rank = Comparator.comparingInt((Student s) -> s.marks())                .reversed()                .thenComparing(s -> s.name());
        TreeSet<Student> board = new TreeSet<>(rank);        board.add(new Student("Aarav", 88));        board.add(new Student("Diya", 92));        board.add(new Student("Kabir", 88));        board.add(new Student("Meera", 75));        board.add(new Student("Aarav", 88));
        System.out.println("Board: " + board);        System.out.println("Topper: " + board.first());        System.out.println("Needs help: " + board.last());        System.out.println("Bottom up: " + board.descendingSet());    }}
Output
Board: [Diya(92), Aarav(88), Kabir(88), Meera(75)]
Topper: Diya(92)
Needs help: Meera(75)
Bottom up: [Meera(75), Kabir(88), Aarav(88), Diya(92)]

What this code does

  • Marks are compared first, highest first because of reversed(). On a tie, names decide, so Aarav and Kabir both stay.
  • Adding the same Aarav(88) again still returns 0 for every key, so a true duplicate is still dropped.

Example 6 · Mistake: a TreeSet of objects with no order

NoOrderDemo.javaJava
import java.util.Set;import java.util.TreeSet;
class Ticket {    private final int number;
    Ticket(int number) {        this.number = number;    }}
public class NoOrderDemo {    public static void main(String[] args) {        Set<Ticket> tickets = new TreeSet<>();        tickets.add(new Ticket(42));        System.out.println("Tickets: " + tickets.size());    }}
Sample output
Exception in thread "main" java.lang.ClassCastException: class Ticket cannot be cast to class java.lang.Comparable (Ticket is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
	at java.base/java.util.TreeMap.compare(TreeMap.java:1569)
	at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:776)
	at java.base/java.util.TreeMap.put(TreeMap.java:785)
	at java.base/java.util.TreeMap.put(TreeMap.java:534)
	at java.base/java.util.TreeSet.add(TreeSet.java:255)
	at NoOrderDemo.main(NoOrderDemo.java:15)

What this code does

  • It compiles, but the very first add fails: the TreeSet tries to treat Ticket as Comparable to place it. The trace shows TreeMap, which a TreeSet uses inside (the Maps module covers it).
  • Fix: make Ticket implements Comparable<Ticket>, or pass a comparator: new TreeSet<>((a, b) -> Integer.compare(a.getNumber(), b.getNumber())).

The fix is a tie-breaker: after the main field, compare a field that is unique, such as the name or roll number, with thenComparing. Then the comparison returns 0 only for truly identical entries.

Rule of thumb: a comparator used in a TreeSet should return 0 only when the two objects are really the same entry.

Trace the code

Trace a comparator on length

import java.util.*;
public class LengthTrap {
public static void main(String[] args) {
Comparator<String> byLength = Comparator.comparingInt(String::length);
TreeSet<String> items = new TreeSet<>(byLength);
items.add("pen");
items.add("book");
items.add("ink");
System.out.println(items);
items.add("bag");
System.out.println(items.size());
}
}

Variables

None yet.

Output

(nothing printed yet)

Line 5This comparator says two words are equal when they have the same length.

Step 1 of 8

Next step

Check your understanding

12 quick questions