Let's say I have a list of People which I need to sort by Age first and then by Name.
Coming from a C#-background, I can easily achieve this in said language by using LINQ:
var list=new List<Person>(); list.Add(new Person(25, "Tom")); list.Add(new Person(25, "Dave")); list.Add(new Person(20, "Kate")); list.Add(new Person(20, "Alice")); //will produce: Alice, Kate, Dave, Tom var sortedList=list.OrderBy(person => person.Age).ThenBy(person => person.Name).ToList();
How does one accomplish this using Kotlin?
This is what I tried (it's obviously wrong since the output of the first "sortedBy" clause gets overridden by the second one which results in a list sorted by Name only)
val sortedList = ArrayList(list.sortedBy { it.age }.sortedBy { it.name })) //wrong
Using sortedWith() function To get a sorted list, without modifying the original list, use the sortedWith() function. It accepts a Comparator which can be used to sort a list by multiple fields, as with the sortWith() function. That's all about sorting a list by multiple fields in Kotlin.
For sorting the list with the property, we use list 's sortedWith() method. The sortedWith() method takes a comparator compareBy that compares customProperty of each object and sorts it. The sorted list is then stored in the variable sortedList .
To sort an Array in descending order in Kotlin, use Array. sortDescending() method. This method sorts the calling array in descending order in-place. To return the sorted array and not modify the original array, use Array.
sortedWith
+ compareBy
(taking a vararg of lambdas) do the trick:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
You can also use the somewhat more succinct callable reference syntax:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With