Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting not working in kotlin by using sortedBy(...)

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?

like image 933
sak Avatar asked Jul 11 '20 16:07

sak


People also ask

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 do you sort a set in Kotlin?

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.

How do I sort a string with Kotlin?

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.


1 Answers

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() }
like image 120
Madhu Bhat Avatar answered Oct 05 '22 22:10

Madhu Bhat