6 - Comparator in Kotlin
6 - Comparator in Kotlin
Comparator in Kotlin
Read Discuss Courses Practice
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.
Extension Functions –
reversed: This function takes a comparator as an argument and returns the comparator with the ordering reversed as
that of the passed comparator.
then: This function combines two comparator, and the second one is used only when the values are equal according
to the first comparator.
fun main(){
val list = ArrayList<Name>()
list.add(Name("Steve","Waugh"))
list.add(Name("Steve","Smith"))
list.add(Name("Virat","Kohli"))
list.add(Name("Kane","Williamson"))
list.add(Name("Joe","Root"))
Output:
thenByDescending: This function returns a descending comparator which converts a value into an instance of type
Comparable and then compares the instances.
fun main() {
val comparator = compareBy<Person> { it.height }
val list = listOf<Person>(
Person(4, 10),
Person(2, 10),
Person(3, 45),
Person(3, 25),
Person(7, 95),
Person(5, 50)
)
Output:
thenComparator: This function returns a Comparator which uses the primary Comparator along with a function to
perform a comparison.
thenDescending: This function combines two comparator, and the second one is used only when the values are
equal according to the first comparator, and sorts the elements in descending order.
fun main(){
val list = listOf<Pair<String,Int>>(
Pair("A",3),
Pair("B",1),
Pair("G",345),
Pair("E",20),
Pair("A",0),
Pair("J",0)
)
Output:
Similar Reads
Sort a List by Specified Comparator in Kotlin Android - Create Group BarChart with Kotlin
Hello World program in Kotlin Android Shared Element Transition with Kotlin
Previous Next
Article Contributed By :
CharchitKapoor
C CharchitKapoor
Company Explore
About Us Job-A-Thon Hiring Challenge
Legal Hack-A-Thon
Careers GfG Weekly Contest
In Media Offline Classes (Delhi/NCR)
Contact Us DSA in JAVA/C++
Advertise with us Master System Design
Master CP
Campus Training Program
Commerce UPSC
Accountancy Polity Notes
Business Studies Geography Notes
Economics History Notes
Management Science and Technology Notes
Income Tax Economics Notes
Finance Important Topics in Ethics
Statistics for Economics UPSC Previous Year Papers