How can you customize the sorting of a TreeSet in Java?
To customize the sorting, you can implement the Comparator interface. The Comparator interface has a compare method that can compare the size of two objects based on the custom sorting rule.
Here is an example where a Person class is created and sorted in a TreeSet based on age.
import java.util.Comparator;
import java.util.TreeSet;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
}
public class Main {
public static void main(String[] args) {
TreeSet<Person> set = new TreeSet<>(new AgeComparator());
set.add(new Person("Alice", 25));
set.add(new Person("Bob", 30));
set.add(new Person("Charlie", 20));
for (Person person : set) {
System.out.println(person.getName() + " - " + person.getAge());
}
}
}
The output is:
Charlie - 20
Alice - 25
Bob - 30
In this example, the AgeComparator class implements the Comparator interface and overrides the compare method to compare Person objects based on their age property. When creating a TreeSet object, the AgeComparator object is passed as a parameter so that the TreeSet will sort according to the rules defined in AgeComparator.