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

Viewed 2836

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?

3 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() }

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".

Related