2

val sortedList = allNovelList.sortedWith(compareBy { (it as Novel).no }) And allNovelList.sortBy { (it as Novel).no }

I have a list of custom object, in which there are integer 'no' is added like id or primary key. From 0 to 9 sorting is working very fine but after 9 , 10 is below to 1.

I am working in Kotlin for Android for first time. I have looked all around the web but I could not get the proper code.

Both lines are giving same sorting. What I want, 1,2,3,....,9,10,11,12...., And What I get after sorting. 1,10,11,2,3,4,5,6...,9

It is sorting like alphabetically.

3
  • 1
    Are you sure that no is integer? Commented Aug 31, 2019 at 17:52
  • no, i am saving it in object as string. Commented Aug 31, 2019 at 17:54
  • 1
    @forpas ,But I got your point what you want to say. let me check it. Thanks for your pointing out the reason. Commented Aug 31, 2019 at 17:55

1 Answer 1

3

As you mentioned in your comment, no is a String, so it sorts it with string sort rules in mind.

You should try this:

val sortedList = allNovelList.sortBy { (it as Novel).no.toInt() }

Make sure that no is an Integer.

Sign up to request clarification or add additional context in comments.

2 Comments

@Muhammad Rehan Accept and upvote an answer if it solves your problem
Yeah, I would love to do, But stackoverflow is not allowing me to upvote because my reputation is less than 15. So, That's why.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.