Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort collection by multiple fields in Kotlin [duplicate]

Tags:

kotlin

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 
like image 876
Fire095 Avatar asked May 16 '16 16:05

Fire095


People also ask

How do you sort a list of objects by multiple fields in Kotlin?

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.

How do I sort an Arraylist 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 .

How does Kotlin sort in descending order?

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.


1 Answers

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)) 
like image 154
Alexander Udalov Avatar answered Sep 20 '22 12:09

Alexander Udalov