Sorting not working in kotlin by using sortedBy(...)
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() }
You are sorting String
list not an Integer
list. Thats the reason P10
came in front of P2
. So, please try below method to sort:
var list: List<String> = mutableListOf("P5","P1","P2","P3","P10")
.sortedWith(compareBy({ it.length }, { it }))
You are sorting strings, not numbers, so Kotlin is sorting them in lexicographical order. That's why "P10" is evaluated as being smaller than "P2".