I am trying to sort this: listOf("P5","P1","P2","P3","P10")
by using val list = categoryList.sortedBy { it }
but what is returning is this: [P1, P10, P2, P3, P5]
, according to my requirement it should return [P1, P2, P3, P5, P10]
so what i am doing wrong here?
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 .
Because the sortWith will do the sorting in-place, we need to use a mutable collection. If we want the result returned as a new collection then we need to use the sortedWith method instead of the sortWith method. For descending order, we can use the reverse method or alternatively define the right Comparator.
To sort an Array of Strings in Kotlin, use Array. sort() method. sort() method sorts the calling array in-place in ascending order. To sort String Array in descending order, call sortDescending() method on this Array.
Since you are sorting by string values directly, you are getting that result. Instead, you can sort by the integer part of the strings as below:
categoryList.sortedBy { it.substring(1).toInt() }
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