Java Intermediate

0% completed

Previous
Next
TreeSet Class With Custom Comparator

While a basic TreeSet sorts its elements in their natural order (e.g., alphabetical for strings, ascending for numbers), sometimes you need a different order. This is where custom comparators come in. A comparator is an object that implements the Comparator interface and defines a custom order for sorting elements. By providing a custom comparator when constructing a TreeSet, you can control how the elements are compared and ordered.

  • Custom Order: Allows sorting in a non-natural order (e.g., descending order, or sorting by a specific property of an object).
  • Comparator Interface: Consists of the single abstract method compare(T o1, T o2), which compares two objects.

Understanding the Comparator Interface

The Comparator interface in Java is declared as:

public interface Comparator<T> { int compare(T o1, T o2); }
  • How compare() Works:
    • Return a Negative Integer: When the first object (o1) should appear before the second object (o2).
    • Return Zero: When both objects are considered equal in terms of ordering.
    • Return a Positive Integer: When the first object (o1) should appear after the second object (o2).

Key Points:

  • If you want to sort numbers in descending order, your comparator should return a negative integer when the first number is greater than the second.
  • For strings sorted by length in ascending order, the comparator should subtract the length of the first string from the length of the second string.

Syntax to Use a Custom Comparator With TreeSet

To use a custom comparator with TreeSet, pass an instance of a Comparator to the TreeSet constructor:

TreeSet<Type> treeSet = new TreeSet<Type>(customComparator);
  • Explanation:
    • customComparator is an instance of a class that implements Comparator<Type>.
    • The TreeSet will use this comparator to order its elements.

Examples

Example: TreeSet with Custom Comparator for Descending Order

In this example, we create a custom comparator to sort integers in descending order. The comparator compares two integers and returns a negative value if the first integer is larger, thus ensuring that higher numbers come first.

Java
Java

. . . .

Example Explanation :

  • Custom Comparator Definition:
    • The DescendingComparator class implements Comparator<Integer> and overrides the compare() method.
    • The method returns b - a, meaning if a is larger than b, the result is negative, placing a before b in the TreeSet for descending order.
  • TreeSet Creation:
    • A new TreeSet is created with new DescendingComparator() passed to the constructor, which instructs the TreeSet to sort integers in descending order.
  • Adding Elements:
    • Integers 10, 5, 20, and 15 are added to the TreeSet.
  • Outcome:
    • The TreeSet automatically orders the elements in descending order: [20, 15, 10, 5].

Example: TreeSet with Custom Comparator for Sorting Strings by Length

This example shows how to use a custom comparator to sort strings based on their length in ascending order. The comparator compares two strings by subtracting the length of the first string from the second string.

Java
Java

. . . .

Example Explanation

  • Custom Comparator Definition:
    • The LengthComparator class implements Comparator<String> and compares strings based on their length.
    • The method subtracts the length of s1 from the length of s2 to sort the strings in ascending order by length.
  • TreeSet Creation:
    • A TreeSet is created with the custom comparator to sort strings by length.
  • Adding Elements:
    • Strings "Java", "Generics", "Code", and "Programming" are added to the TreeSet.
  • Outcome:
    • The TreeSet displays the strings ordered by their length, from shortest to longest.

Custom comparators allow you to define specific ordering criteria for a TreeSet that differ from the natural ordering of its elements. By understanding how to implement and use the Comparator interface, you can control the order of elements in a TreeSet precisely, ensuring that your collections are sorted exactly as needed.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next