The following article describes How does TreeSet Maintain the Order of elements.
Unlike the Set interface, TreeSet is a class in Java collections. Furthermore, it is backed by a TreeMap
structure. Also, the TreeSet represents a sorted set. In other words, it maintains the order of the elements based on the elements’ natural ordering or a custom order specified by a Comparator
.
The elements in a TreeSet
are sorted in ascending order by default, based on the natural ordering of the elements. If the elements are of a custom class, then the class must implement the Comparable
interface, and the elements will be sorted based on the compareTo
method defined in the class.
If you want to use custom order
, you can provide a Comparator
object to the TreeSet
constructor. The Comparator
will then be used to determine the order of the elements in the TreeSet
.
Here is an example of how to use TreeSet
with a custom ordering:
csharpCopy codeimport java.util.Comparator;
import java.util.TreeSet;
public class Main {
static class Employee {
int id;
String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
public static void main(String[] args) {
Comparator<Employee> comparator = new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return Integer.compare(o1.id, o2.id);
}
};
TreeSet<Employee> set = new TreeSet<>(comparator);
set.add(new Employee(1, "John"));
set.add(new Employee(2, "Jane"));
set.add(new Employee(3, "Jim"));
for (Employee employee : set) {
System.out.println(employee);
}
}
}
In conclusion, TreeSet
uses a TreeMap
structure to maintain the order of the elements based on the elements’ natural ordering or a custom order specified by a Comparator
. It provides a fast and efficient way to store and retrieve sorted elements in Java.
Further Reading
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
