If you’ve recently received a Java homework assignment involving TreeSet, like it you might be staring at the prompt wondering: Why does my order keep changing? What is a Comparator? And how do I sort custom objects? You are not alone.
The TreeSet is one of Java’s most powerful collection classes, but it introduces concepts—sorted sets, natural ordering, and comparators—that often trip up students. This article breaks down exactly what you need to know to complete your homework on TreeSet, understand sorted sets, and implement custom comparators.
What is a TreeSet?
In Java, a TreeSet is a collection that stores unique elements in a sorted tree structure. Unlike a HashSet, which stores items in no particular order (using a hash table), a TreeSet automatically arranges its elements in ascending order.
Consider this simple code:
java
TreeSet<Integer> numbers = new TreeSet<>(); numbers.add(5); numbers.add(1); numbers.add(3); System.out.println(numbers); // Output: [1, 3, 5]
Notice you inserted 5, 1, 3, but the output is sorted. This automatic sorting is the core feature you’ll be tested on.
Why Use a TreeSet?
- Sorted order – Elements are always maintained in sorted sequence.
- Unique elements – No duplicates (like all Sets).
- Logarithmic time –
add(),remove(), andcontains()are O(log n) (faster thanArrayListfor large data, slower thanHashSet). - Navigable features – Methods like
lower(),floor(),ceiling(), andhigher()let you find nearest matches.
Natural Ordering vs. Custom Comparators
This is the single most common source of homework confusion. Let’s clarify it.
Natural Ordering (Comparable)
Every class in Java can define its “natural” sorting order by implementing the Comparable<T> interface and overriding compareTo(). For example, String sorts alphabetically; Integer sorts numerically.
If you add objects to a TreeSet that do not implement Comparable, you will get a runtime error:java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
Example of natural ordering in a custom class:
java
class Student implements Comparable<Student> {
String name;
int id;
Student(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.id, other.id); // sort by id ascending
}
}
Now a TreeSet<Student> will automatically sort by ID.
Custom Ordering with Comparator
Your homework will often ask: “Sort by name instead of ID” or “Sort in descending order.” Since you cannot change the class (or you need multiple sort orders), you use a Comparator.
A Comparator is a separate strategy object that tells TreeSet how to compare two elements.
Syntax:
java
Comparator<MyClass> comparator = (a, b) -> a.field.compareTo(b.field); TreeSet<MyClass> set = new TreeSet<>(comparator);
Homework example: Sort students by name length, then by name.
java
Comparator<Student> byNameLengthThenName = Comparator
.comparingInt((Student s) -> s.name.length())
.thenComparing(s -> s.name);
TreeSet<Student> students = new TreeSet<>(byNameLengthThenName);
Common Homework Tasks and How to Solve Them
Task 1: Removing Duplicates While Sorting
Your professor gives an unsorted list with duplicates and asks you to return a sorted unique list.
Solution: Add all elements to a TreeSet. It automatically discards duplicates and sorts.
java
List<Integer> raw = Arrays.asList(4, 2, 4, 1, 3, 2); TreeSet<Integer> sortedUnique = new TreeSet<>(raw); System.out.println(sortedUnique); // [1, 2, 3, 4]
Task 2: Reverse Order
“Display the set in descending order.”
Solution: Use Collections.reverseOrder() or a custom comparator.
java
TreeSet<Integer> reverseSet = new TreeSet<>(Collections.reverseOrder()); reverseSet.addAll(Arrays.asList(1, 3, 2)); System.out.println(reverseSet); // [3, 2, 1]
Task 3: Working with Custom Objects
“Create a TreeSet of Book objects sorted by publication year, then by title.”
Solution: Chain comparators.
java
class Book {
String title;
int year;
// constructor, getters
}
Comparator<Book> byYearThenTitle = Comparator
.comparingInt(Book::getYear)
.thenComparing(Book::getTitle);
TreeSet<Book> library = new TreeSet<>(byYearThenTitle);
Task 4: Finding Subsets (NavigableSet features)
TreeSet implements NavigableSet, giving you powerful subset methods.
headSet(toElement)– elements less than toElementtailSet(fromElement)– elements greater than or equalsubSet(from, to)– range
Homework use case: “Print all students with scores between 70 and 90.”
java
TreeSet<Integer> scores = new TreeSet<>(Arrays.asList(55, 72, 88, 91, 68, 79)); System.out.println(scores.subSet(70, true, 90, true)); // [72, 79, 88]
Frequent Pitfalls (And How to Avoid Them)
Pitfall 1: Forgetting the Comparator in the Constructor
If your class does not implement Comparable and you create new TreeSet<MyClass>() without a comparator, you get a ClassCastException at runtime when you add the first element.
Fix: Always provide a comparator or ensure the class implements Comparable.
Pitfall 2: Inconsistent with equals()
TreeSet uses compareTo() or compare() to determine uniqueness, not equals(). If compareTo() returns 0 for two different objects, TreeSet treats them as duplicates and one is lost.
Homework alert: If you sort by id but two students have same ID but different names, only one is stored. Related Site Make your comparison include all fields that define uniqueness.
Pitfall 3: Mutating Elements After Insertion
If you change a field that is used in comparison after adding an object to a TreeSet, the set will not reorder automatically. The structure will break, and methods like contains() will behave unpredictably.
Rule: Make objects in a TreeSet immutable, or remove, modify, then re-add.
When Should You Use TreeSet vs. Other Collections?
Your homework might ask you to justify your choice. Here’s a cheat sheet:
| Collection | Ordering | Duplicates | Performance | Use when |
|---|---|---|---|---|
TreeSet | Sorted | No | O(log n) | Need sorted unique elements + range queries |
HashSet | Unsorted | No | O(1) avg | Only need uniqueness, no ordering |
ArrayList | Insertion order | Yes | O(n) search | Need index access or duplicates |
PriorityQueue | Heap order | Yes | O(log n) insert | Always need smallest/first element |
Sample Homework Problem – Fully Worked
Problem: Write a program that takes a list of employee names and salaries, stores them in a TreeSet sorted by salary (highest first), and then prints the top 3 earners. If salaries are equal, sort alphabetically by name.
Solution:
java
import java.util.*;
class Employee {
String name;
int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return name + " ($" + salary + ")";
}
}
public class Main {
public static void main(String[] args) {
Comparator<Employee> bySalaryDescThenName = Comparator
.comparingInt((Employee e) -> e.salary)
.reversed()
.thenComparing(e -> e.name);
TreeSet<Employee> employees = new TreeSet<>(bySalaryDescThenName);
employees.add(new Employee("Alice", 70000));
employees.add(new Employee("Bob", 85000));
employees.add(new Employee("Charlie", 70000));
employees.add(new Employee("Diana", 95000));
System.out.println("Top 3 earners:");
int count = 0;
for (Employee e : employees) {
if (count++ >= 3) break;
System.out.println(e);
}
}
}
Output:
text
Top 3 earners: Diana ($95000) Bob ($85000) Alice ($70000)
Final Tips for Your Homework
- Read the requirement carefully – Does it ask for natural ordering or a custom comparator?
- Test edge cases – Empty set, null values (TreeSet does NOT allow null), duplicate objects.
- Use method references –
Comparator.comparing(Employee::getSalary)is cleaner than lambdas. - Remember that TreeSet is not thread-safe – Not usually needed for homework, but good to know.
Understanding TreeSet, sorted sets, and comparators will not only help you ace your homework but also make you a better Java developer. The ability to elegantly manage sorted, click this unique data is a skill that appears in real-world applications—from leaderboards to autocomplete features.
Now go implement that comparator and watch your TreeSet fall perfectly into order!