Java provides two interfaces to sort objects using data members of the class:
- Comparable
- Comparator
- Natural Ordering: The default way to order objects based on their intrinsic properties (like age in the
Person
class). - Custom Ordering: User-defined ways to order objects based on specific needs or multiple attributes (like sorting
Person
objects by name or by age in descending order).
Comparable
Definition:
The Comparable
interface is used to define the natural ordering of objects of a class. A class implements this interface to allow objects of that class to be compared to one another, typically based on one attribute.
Comparator
Definition:
The Comparator
interface is used to define a custom ordering of objects. It allows for comparison of two objects and can be implemented to create multiple different sorting strategies.
When Comparable & Comparator returns 0,1 and -1
In the context of Comparable
and Comparator
, the methods compareTo
and compare
return integer values that indicate the relative order of the objects being compared. Here’s what the return values mean:
Return Values
- 0: Indicates that the two objects are considered equal in terms of the sorting criteria.
- Positive Value (1): Indicates that the first object is greater than the second object.
- Negative Value (-1): Indicates that the first object is less than the second object.
Comparator
for the Book
class to sort by the author's name.
- You can use a
Comparator
to sort the list by the new attribute. If the list is already sorted by one attribute, using a secondary sorting strategy (e.g., usingthenComparing
) can maintain the previous order where applicable.
3. In a system that allows for dynamic sorting criteria (e.g., user can choose sort by age or name), how would you design the sorting mechanism?
- Implement a method that accepts a
Comparator
as a parameter. Allow the user to select the sorting criteria, create the correspondingComparator
, and pass it to the sorting method.
4. If you need to sort a list of products by price in ascending order and then by name in descending order, how would you implement this using Comparator
?
thenComparing() implementation |
We can use Comparator.nullsFirst()
or Comparator.nullsLast()
to define how null values should be treated. Here are examples for both approaches.
Comparator.nullsFirst ensures that null values come first.
Comparator.nullsLast ensures that null values come last.
This approach sorts null values before non-null values.
6. Write the code how the streams will be used to sort the person object based on name and age ?
Using Comparable (only based on age)
Comparator (based on name)
7. What all datastructure uses comparable and comparator
how Comparable
and Comparator
are used in Java for sorting and the underlying data structures involved.
Post a Comment