Kotlin Comparators

Learn via video courses
Topics Covered

Overview

In Kotlin, comparators are used to define the order of elements in a collection or to compare objects. The Comparator interface enables custom rules, and Comparable supports natural ordering within a class.

Kotlin's standard library offers functions like compareBy and thenBy for creating Kotlin comparators. This flexibility empowers users to implement specific sorting logic, enhancing element order management in Kotlin collections.

Understanding the Comparator Interface

In Kotlin, the Comparator interface is used to define a custom way to compare objects for sorting purposes. The Kotlin Comparator interface has a single method called compare, which you need to implement to specify the logic for comparing two objects.

Example :

Output :

Explanation:

  • The example utilizes the Comparator interface to sort a list of Person objects by age and name.
  • An ageComparator is crafted to compare Person objects based on their age, and the sortedWith function efficiently organizes the list.
  • Similarly, a nameComparator compares Person objects by names using the compareTo function, and sortedWith is used for sorting by name.

Simplified Code with compareBy:

In this version, the compareBy function simplifies the creation of comparators by taking a lambda expression that specifies the property to be compared.

Implementing Comparators in Kotlin

Here are the implementations of different Comparator techniques in Kotlin:

Using Comparator with compareBy

The compareBy function in Kotlin is a convenient way to create comparators for sorting based on one or more properties of objects.

Output :

Using Comparator with multiple fields using thenComparing

The thenComparing in Kotlin, used with compareBy or other comparators, establishes a secondary sorting level when primary criteria tie, enabling hierarchical sorting based on multiple properties.

Output:

Advanced Comparator Techniques

Reversing Order with reversed

reversed() is a Kotlin extension for the Comparator interface, creating a new comparator that reverses the original order, sorting elements oppositely.

Example:

Output :

Combining Comparators with then and thenBy

then Function:

then in Kotlin combines two comparators, applying the second when values are equal according to the first, establishing a secondary sorting criterion.

Example

Output :

thenBy Function:

thenBy converts type instances to Comparable instances and compares them, serving as additional sorting criteria.

Example :

Output:

Fine-Tuning with thenByDescending and thenDescending

thenByDescending Function:

thenByDescending combines two comparators, applying the second when values are equal according to the first, and sorts elements in descending order based on the second comparator.

Example

Output :

thenDescending Function:

thenDescending reverses the order of the existing comparator, applying descending order to the elements.

Example :

Output :

In this example, ascendingOrder is combined with thenDescending to first sort the list in ascending order and then reverse the entire list, achieving descending order.

Custom Comparators with thenComparator

The thenComparator function is part of Kotlin's Comparator API, offering a way to extend sorting logic by introducing a custom comparison function.

Example:

Suppose we have a list of students, and we want to sort them first by their grades in ascending order and then, if the grades are equal, sort them by the length of their names in descending order:

Output :

Comparators vs Comparable in Kotlin

AspectComparableComparator
Interface vs. ClassInterface (Comparable<T>)Interface (Comparator<T>)
PurposeDefines natural ordering within a classDefines external ordering for a class
Method to ImplementcompareTo(T obj): part of Comparable interfacecompare(T obj1, T obj2): part of Comparator interface
Ordering TypeNatural ordering intrinsic to the objectExternal ordering, can be defined for multiple criteria
Intrinsic vs. ExtrinsicIntrinsic, part of the class being comparedExtrinsic, separate from the class
Number of Sorting CriteriaSupports a single sorting criterionAllows for multiple sorting criteria
UsageAutomatically used by sorting methods (Collections.sort(), sorted())Explicitly specified when sorting using external criteria (Collections.sort(list, comparator), sortedWith(comparator))

Conclusion

  • Kotlin Comparators simplify object comparisons, offering flexibility in sorting.

  • The Comparator interface is essential for implementing precise custom sorting in Kotlin applications.

  • Kotlin's flexible sorting strategies, like compareBy and thenComparing, simplify property-based sorting. Reversed and thenDescending enhance versatility for descending order.

  • Comparable offers default sorting, applied automatically, while Comparator allows explicit, flexible custom or multiple criteria sorting.