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?
-
your array will be alaways ("P5","P1","P2","P3","P10") ?– Shalu T DCommented Jul 11, 2020 at 16:24
Add a comment
|
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 }))
-
Can you please tell me how this working? I am not able to understand this expression.– sakCommented 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. Commented Jul 13, 2020 at 6:39
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".