15

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?

msrd0
  • 7,816
  • 9
  • 47
  • 82
VTR2015
  • 429
  • 2
  • 6
  • 15

5 Answers5

16

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.

weston
  • 54,145
  • 21
  • 145
  • 203
7

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.

dkb
  • 4,389
  • 4
  • 36
  • 54
msrd0
  • 7,816
  • 9
  • 47
  • 82
5

You can use mutableList's extension methods. like

list.sort()
list.sortBy{it.value}
list.sortByDescending()
list.sortByDescending{it.value}
TOUSIF
  • 285
  • 5
  • 4
3

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 }
  • 1
    you can sort with ```var sortedByName = myObjectList.sortedBy { it.name }``` And beside that you can sort with ```myObjectList.sortedByDescending { it.name }``` – mohsen Jan 13 '20 at 08:11
1

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
Luca Murra
  • 1,848
  • 14
  • 24