Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort data from a MutableList in Kotlin

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?

like image 650
VTR2015 Avatar asked Oct 21 '17 22:10

VTR2015


5 Answers

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.

like image 184
msrd0 Avatar answered Oct 13 '22 21:10

msrd0


You can use mutableList's extension methods. like

list.sort()
list.sortBy{it.value}
list.sortByDescending()
list.sortByDescending{it.value}
like image 22
TOUSIF AHAMMAD Avatar answered Oct 13 '22 22:10

TOUSIF AHAMMAD


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 }
like image 24
Moises Orduno Avatar answered Oct 13 '22 22:10

Moises Orduno


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
like image 36
Luca Murra Avatar answered Oct 13 '22 21:10

Luca Murra


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.

like image 44
weston Avatar answered Oct 13 '22 21:10

weston