I'm new to Kotlin and need to ask some questions about ordering a MutableList<MyObject>
. As I understand it, I can do a myMutableList.sortBy {it.int}
and a myMutableList.sortByDescending {it.int}
for both Int
and String
. But return is always a Unit
and not a MutableList
.
Where am I going wrong and how do I proceed?
The kotlin functions sort
, sortBy
, sortWith
etc. all sort the items in the list itself.
From the documentation of sort
:
Sorts the array in-place according to the natural order of its elements.
If you don't want to sort the elements in-place but rather return a sorted list (your base doesn't need to be a MutableList
), you can use sorted
, sortedBy
, sortedWith
, etc:
Returns a list of all elements sorted according to their natural sort order.
You can use mutableList's extension methods. like
list.sort()
list.sortBy{it.value}
list.sortByDescending()
list.sortByDescending{it.value}
You can do something like this with the properties of the object inside the list, so let's say you have an object with a string and a number
data class MyObject(var name:String,var number:Int)
add some values to it
val myObjectList: MutableList<MyObject>? = mutableListOf()
myObjectList!!.add(MyObject("C",3))
myObjectList.add(MyObject("B",1))
myObjectList.add(MyObject("A",2))
And then you can sort it by either one of its properties, it'll return a mutable list with the sorted values
var sortedByName = myObjectList.sortedBy { myObject -> myObject.name }
var sortedByNumber = myObjectList.sortedBy { myObject -> myObject.number }
To sort a mutable list you can use:
Collections.sort(myMutableList)
Collections.reverse(myMutableList) //To sort the list by descending order
And in kotlin you can use the contract kotlin stdlib instruction, and it becomes:
myMutableList.sort()
myMutableList.reverse() //To sort the list by descending order
And then you can call myMutableList
and it's order is changed, like this:
val myMutableList = mutableListOf(8,5,4,6)
System.out.println("myMutableList: ${myMutableList[0]}")
myMutableList.sort()
System.out.println("myMutableList: ${myMutableList[0]}")
Output:
myMutableList: 8
myMutableList: 4
Mutable means changeable, so it makes sense that rather than sortBy
returning a new list, the order of the items has changed "in place" in the current list.
Try looking at the order of the items in myMutableList
after the sortBy
and you will see they are now in the order requested.
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