Sub topic 11
Ordered Sets: LinkedHashSet and TreeSet
A HashSet keeps each element only once, but it makes no promise about order. If you print it, the elements can come out in any order. Sometimes you need unique elements and a predictable order as well. Java gives you two more Set implementations for this.
LinkedHashSetis a set that remembers the order in which you added elements.TreeSetis a set that keeps its elements sorted.
Both still reject duplicates, just like HashSet.
Seeing the Three Sets Side by Side
The program below puts the same words into all three kinds of set. The word "apple" appears twice in the input, so each set stores it only once.
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class OrderedSetsDemo {
public static void main(String[] args) {
List<String> input = List.of("pear", "apple", "fig", "apple", "banana");
Set<String> hash = new HashSet<>(input);
Set<String> linked = new LinkedHashSet<>(input);
Set<String> tree = new TreeSet<>(input);
System.out.println(hash); // order not guaranteed
System.out.println(linked); // [pear, apple, fig, banana]
System.out.println(tree); // [apple, banana, fig, pear]
}
}The LinkedHashSet prints the words in the order they first arrived. The TreeSet prints them in alphabetical order, which is the natural order for String.
LinkedHashSet: Insertion Order
A LinkedHashSet works like a HashSet with an extra list running through it. That list records the order of insertion. Adding an element that is already present does not move it.
Use it when you want to remove duplicates but keep the original order. One example is cleaning up a list of user tags without shuffling them.
TreeSet: Sorted Order
A TreeSet stores elements in a sorted structure called a tree. Every time you add an element, it goes into its correct sorted place. Because the set is always sorted, it has handy methods such as first() and last().
By default, TreeSet uses the elements' natural order, which comes from Comparable. You can also pass a Comparator to choose a different order.
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> scores = new TreeSet<>();
scores.add(72);
scores.add(95);
scores.add(60);
System.out.println(scores); // [60, 72, 95]
System.out.println(scores.first()); // 60
System.out.println(scores.last()); // 95
TreeSet<String> byLength = new TreeSet<>(Comparator.comparing(String::length));
byLength.add("fig");
byLength.add("kiwi");
byLength.add("pear");
System.out.println(byLength); // [fig, kiwi]
}
}A TreeSet that uses natural order also cannot hold null, because null cannot be compared with anything.
Which Set Should You Pick?
| Set | Order when you loop | Speed of add and contains |
|---|---|---|
| `HashSet` | No guaranteed order | Fastest |
| `LinkedHashSet` | Insertion order | Fast, uses a bit more memory |
| `TreeSet` | Sorted order | Slower, grows with size (log n) |
Exercise
You add the numbers 5, 3, 5, 9, 1 to a LinkedHashSet and to a TreeSet. What does each set print?
Show answer
The LinkedHashSet prints [5, 3, 9, 1], because it keeps insertion order and ignores the second 5. The TreeSet prints [1, 3, 5, 9], because it keeps numbers in sorted order.
Exercise
A TreeSet<String> built with Comparator.comparing(String::length) gets "cat", "dog", and "horse" added. How many elements does it hold, and why?
Show answer
It holds 2 elements: "cat" and "horse". The comparator says "dog" equals "cat" because both have length 3, so the TreeSet treats "dog" as a duplicate and does not add it.