8

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?

1
  • your array will be alaways ("P5","P1","P2","P3","P10") ?
    – Shalu T D
    Commented Jul 11, 2020 at 16:24

3 Answers 3

14

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() }
0
8

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 }))
2
  • Can you please tell me how this working? I am not able to understand this expression.
    – sak
    Commented Jul 12, 2020 at 7:52
  • 1
    @sak Here the compareBy is passed with 2 comparators, the length of the string { it.length } and the string value { it }. That ensures that P10 doesn't come just next to P1.
    – Madhu Bhat
    Commented Jul 13, 2020 at 6:39
5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.