0

Let's say I have an array list of BaiGiangModel which I need to sort by title first. I was able to sort it using this code

list.sortWith(compareBy({it.title}))

However, the result is not perfect. Instead of getting 9 Number in front of 10 Number order, I get 10 Number then 9 Number. Everything else is fine. Any suggestions? Below is my array list.

    var list= ArrayList<BaiGiangModel>()
    val model1 = BaiGiangModel("10 Number")
    val model2 = BaiGiangModel("9 Number")
    val model3 = BaiGiangModel("A Number")

    list.add(model1)
    list.add(model2)
    list.add(model3)

result print is: 10 Number, 9 Number, A Number

or let say I add Number 1, Number 19, Number 9 to my current list, my sorted result returns this

10 Number, 9 Number, A Number, Number 1, Number 19, Number 9

  • 1
    That's because "1" comes before "9" in the alphabetical order. "10 Number" and "9 Number" are strings. – Naetmul Jan 25 '18 at 05:42
  • 1
    val model2 = BaiGiangModel("09 Number","www.two.com") --- This statement will help fix the issue ONLY for this case and help you understand the issue. For generic solution, you need to tell more about all possible input patterns, i.e. will it have "Two numbers"? – Sarwar Erfan Jan 25 '18 at 05:46
  • You're trying to sort strings, not a number so that's a right result. – xxx Jan 25 '18 at 05:47
  • I understand and that's why I'm hoping someone can help me out on this –  Jan 25 '18 at 05:48
  • You might want too look into [https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/](natural sorting) also https://stackoverflow.com/questions/34518/natural-sorting-algorithm – leonardkraemer Jan 25 '18 at 06:04

0 Answers0