In programming contexts, as there arises a need for a new type, there is also a major task of ordering the instances of a type. To compare two instances of a type we implement Comparable interface. However, since in ordering instances they must be compared automatically and also since the order can vary according to various parameters, Kotlin provides a simple Comparator interface. This interface compares two objects of a type and arranges them in an order. Function –compare: This function compares two instance of a type and returns zero if both are equal, a negative number if second instance is bigger otherwise returns a positive number. abstract fun compare(a: T, b: T): IntExtension Functions –reversed: This function takes a comparator as an argument and returns the comparator with the ordering reversed as that of the passed comparator. fun <T> Comparator<T>.reversed(): Comparator<T> Example to demonstrate the compare, then and reversed functions.
Output: The list is: [Steve Waugh, Steve Smith, Virat Kohli, Kane Williamson, Joe Root] List sorted according to first name [Joe Root, Kane Williamson, Steve Waugh, Steve Smith, Virat Kohli] List sorted according to first name and last name [Joe Root, Kane Williamson, Steve Smith, Steve Waugh, Virat Kohli] List reverse sorted [Virat Kohli, Steve Waugh, Steve Smith, Kane Williamson, Joe Root]thenBy: This function converts the type instances to an instance of type Comparable and then compares them using these instances. fun <T> Comparator<T>.thenBy( selector: (T) -> Comparable<*>? ): Comparator<T> Example to demonstrate the thenBy and thenByDescending functions
Output: Sorted first according to height then by weight [Height = 2, Weight = 10, Height = 3, Weight = 25, Height = 3, Weight = 45, Height = 4, Weight = 10, Height = 5, Weight = 50, Height = 7, Weight = 95] Sorted first according to weight then by descending order in height [Height = 4, Weight = 10, Height = 2, Weight = 10, Height = 3, Weight = 25, Height = 3, Weight = 45, Height = 5, Weight = 50, Height = 7, Weight = 95] Example to demonstrate the thenComparator and thenDescending functions.
Output: Pairs sorted by String then by Integers [(A, 0), (A, 3), (B, 1), (E, 20), (G, 345), (J, 0)] Pairs sorted by Integers then by Strings in Descending order [(J, 0), (A, 0), (B, 1), (A, 3), (E, 20), (G, 345)] |