In Java, sorting of collections can be done using two main interfaces: Comparable and Comparator. Both of these interfaces play a crucial role in defining the order in which objects are sorted.
The Comparable interface is used to define the natural ordering of objects. It is implemented by the class whose objects are to be compared. The class needs to override the compareTo()
method, which compares the current object with the specified object.
The Comparator interface, on the other hand, is used when you want to define multiple ways of sorting the objects. This interface is implemented in a separate class and defines the compare()
method. It allows you to create different sorting strategies without changing the original class.
// Example of Comparable
class Employee implements Comparable {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
// Overriding compareTo method
public int compareTo(Employee e) {
return this.age - e.age; // sorting by age
}
}
// Example of Comparator
class EmployeeNameComparator implements Comparator {
public int compare(Employee e1, Employee e2) {
return e1.name.compareTo(e2.name); // sorting by name
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?