Sub topic 11
Ordered Sets: LinkedHashSet and TreeSet
In the chapter on HashSet, you saw that a set keeps each element only once. You also saw that a HashSet makes no promise about order. When you print it, the elements can come out in any order, and that order can change as the set grows.
Often that is fine. Sometimes it is not. You might want to show tags in the order a user typed them, or list student scores from lowest to highest. Java has two other Set classes for these jobs:
LinkedHashSetkeeps elements in insertion order, which is the order you added them.TreeSetkeeps elements in sorted order, which is the order set bycompareToor by aComparator.
Both still follow the main rule of every set: no duplicates.
The three sets side by side
The quickest way to see the difference is to add the same words to all three sets.
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[] words = {"banana", "apple", "cherry", "apple"};
Set<String> hash = new HashSet<>();
Set<String> linked = new LinkedHashSet<>();
Set<String> tree = new TreeSet<>();
for (String w : words) {
hash.add(w);
linked.add(w);
tree.add(w);
}
System.out.println(hash); // some order, not guaranteed
System.out.println(linked); // [banana, apple, cherry]
System.out.println(tree); // [apple, banana, cherry]
}
}Each set has three elements, because the second "apple" was rejected. Only the order differs:
HashSetprints in whatever order its internal table produces.LinkedHashSetprints in the order the words first arrived.TreeSetprints in alphabetical order, which is the natural order forString.
Notice that the variables use the type Set<String>. The code that uses the set does not care which kind it is. You choose the ordering in one place, at the new call.
LinkedHashSet: remembering the order you added things
A LinkedHashSet is a HashSet with one extra feature. Next to its hash table, it keeps a linked list, which is a chain where each element points to the next one. That chain records the order in which elements were added. When you loop over the set, Java follows the chain.
Because the hash table is still there, add, remove, and contains are about as fast as in a HashSet. The chain costs a little extra memory, and that is the only real price.
Re-adding does not move an element
One detail surprises many beginners. If you add an element that is already in the set, nothing happens. The element keeps its original place.
import java.util.LinkedHashSet;
import java.util.Set;
public class ReAddDemo {
public static void main(String[] args) {
Set<String> visited = new LinkedHashSet<>();
visited.add("home");
visited.add("news");
visited.add("sports");
System.out.println(visited.add("home")); // false
System.out.println(visited); // [home, news, sports]
visited.remove("home");
visited.add("home");
System.out.println(visited); // [news, sports, home]
}
}To move an element to the end, remove it first and then add it again.
A common use: removing duplicates but keeping order
Say you have a list with repeats and want the repeats gone. A HashSet would scramble the order. A LinkedHashSet keeps it:
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
public class DedupDemo {
public static void main(String[] args) {
List<String> emails = List.of("[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]");
List<String> unique = new ArrayList<>(new LinkedHashSet<>(emails));
System.out.println(unique); // [[email protected], [email protected], [email protected]]
}
}TreeSet: always sorted
A TreeSet stores its elements in a red-black tree, which is a balanced tree structure that keeps items sorted as you add them. You never call a sort method. The set is sorted at all times.
Keeping the tree sorted takes work. add, remove, and contains take time that grows slowly with the size of the set. Computer scientists write this as O(log n). A set of one million elements needs about 20 steps per lookup. A HashSet needs roughly a constant number of steps, so it is faster when you don't need order.
How TreeSet decides the order
A TreeSet needs a way to compare two elements. It gets one of two ways:
- Natural order. The element class implements
Comparableand has acompareTomethod.String,Integer, andLocalDateall do this. - A Comparator. You pass a
Comparatorto the constructor, as you saw in the sorting chapter.
If you do neither, the program compiles. Then the first add (or the second, depending on the case) throws a ClassCastException at run time, because Java cannot compare the elements.
Extra methods for sorted data
Since a TreeSet knows the order, it can answer questions a plain Set can't. To use these methods, declare the variable as TreeSet (or NavigableSet) instead of Set.
import java.util.List;
import java.util.TreeSet;
public class NavigateDemo {
public static void main(String[] args) {
TreeSet<Integer> scores = new TreeSet<>(List.of(42, 7, 19, 88, 7));
System.out.println(scores); // [7, 19, 42, 88]
System.out.println(scores.first()); // 7
System.out.println(scores.last()); // 88
System.out.println(scores.floor(20)); // 19 (largest <= 20)
System.out.println(scores.ceiling(20)); // 42 (smallest >= 20)
System.out.println(scores.higher(42)); // 88 (smallest > 42)
System.out.println(scores.lower(7)); // null (nothing < 7)
System.out.println(scores.headSet(42)); // [7, 19] (below 42)
System.out.println(scores.tailSet(42)); // [42, 88] (42 and above)
System.out.println(scores.descendingSet()); // [88, 42, 19, 7]
}
}| Method | Returns |
|---|---|
| `first()` / `last()` | Smallest / largest element |
| `floor(x)` | Largest element less than or equal to `x`, or `null` |
| `ceiling(x)` | Smallest element greater than or equal to `x`, or `null` |
| `lower(x)` / `higher(x)` | Strictly less / strictly greater neighbor, or `null` |
| `headSet(x)` | Elements less than `x` |
| `tailSet(x)` | Elements greater than or equal to `x` |
| `descendingSet()` | The same elements in reverse order |
The big TreeSet gotcha: comparison decides duplicates
A HashSet uses equals and hashCode to decide whether two elements are the same. A TreeSet does not use them at all. It treats two elements as the same when the comparison returns 0.
That matters when your Comparator looks at only part of the element:
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class LengthGotcha {
public static void main(String[] args) {
Set<String> byLength = new TreeSet<>(Comparator.comparing(String::length));
byLength.add("fig");
byLength.add("kiwi");
System.out.println(byLength.add("pear")); // false: same length as kiwi
byLength.add("apple");
System.out.println(byLength); // [fig, kiwi, apple]
Set<String> fixed = new TreeSet<>(
Comparator.comparing(String::length)
.thenComparing(Comparator.naturalOrder()));
fixed.add("fig");
fixed.add("kiwi");
fixed.add("pear");
fixed.add("apple");
System.out.println(fixed); // [fig, kiwi, pear, apple]
}
}The first set threw away "pear" without any error, because "pear" and "kiwi" both have length 4 and the comparator returned 0. The fix adds a tie-breaker with thenComparing, so two different words never compare as equal.
The same rule explains String.CASE_INSENSITIVE_ORDER. A TreeSet built with it keeps "Apple" or "apple", whichever came first, and rejects the other. Sometimes that is exactly what you want.
Null is not allowed
HashSet and LinkedHashSet accept one null. A TreeSet with natural ordering throws NullPointerException when you add null, because it cannot call compareTo on null.
Choosing among the three sets
| Row | `HashSet` | `LinkedHashSet` | `TreeSet` |
|---|---|---|---|
| Iteration order | None promised | Insertion order | Sorted order |
| Add / contains / remove | About O(1) | About O(1) | O(log n) |
| Decides duplicates with | `equals` + `hashCode` | `equals` + `hashCode` | `compareTo` or `Comparator` |
| Allows `null` | Yes, one | Yes, one | No (natural order) |
| Extra memory | Low | Medium | Medium |
| Navigation methods | No | No | Yes |
A simple rule: start with HashSet. Switch to LinkedHashSet when the order you added things matters. Switch to TreeSet when you need sorted output or questions like "what is the next value above 50?"
Exercise
You add "dog", "cat", "dog", "ant" to a LinkedHashSet and, separately, to a TreeSet with natural order. What does each print?
Show answer
The LinkedHashSet prints [dog, cat, ant], which is the order of first insertion. The second "dog" is ignored. The TreeSet prints [ant, cat, dog], which is alphabetical order.
Exercise
A TreeSet<Integer> holds [10, 20, 30, 40]. What do floor(25), ceiling(40), higher(40), and headSet(30) return?
Show answer
floor(25) returns 20, ceiling(40) returns 40, higher(40) returns null, and headSet(30) returns [10, 20] because headSet excludes the given value.
Exercise
A class Student has fields name and grade. A programmer stores students in new TreeSet<>(Comparator.comparing(Student::getGrade)). Two different students both have grade 90, but only one appears in the set. Why, and how do you fix it?
Show answer
A TreeSet treats elements as duplicates when the comparator returns 0, and this comparator returns 0 for any two students with the same grade. Add a tie-breaker, for example Comparator.comparing(Student::getGrade).thenComparing(Student::getName), so that different students never compare as equal.