1

In Android application development using Kotlin, which would be the efficient way to sort a JSON array which got objects having dates as property values.

I want to sort my response with date and pick the latest created item. For example, my list response is

[
    {
        name : "Joseph"
        enrolled_at : "2019-12-17 14:16:51"
    },
    {
        name : "Infant"
        enrolled_at : "2019-12-20 10:06:22"
    },
    {
        name : "Raj"
        enrolled_at : "2020-02-10 07:19:16"
    }
]

I want to sort this with "enrolled_at" property date to get the recent enrolled item. The original response is huge and so I cannot get the real response here.

What would be the efficient way to sort the dates using Kotlin. Tried with sortedWith and other collections in Kotlin. Looking for suggestions.

3
  • so, what's wrong with collections sorting methods? Commented Jul 15, 2020 at 10:08
  • You need to convert string date into an actual date and then use sortedWith or sortedBy Commented Jul 15, 2020 at 10:10
  • did you try sortyBy ? Commented Jul 15, 2020 at 10:11

1 Answer 1

8

First, you need to create the method that converts that String into a Date in order for your array to be sortable.

And assuming you're converting that JSON to a list of users of type:

data class User(val name: String, val enrolled_at: String)

Using the ability to create extensions in Kotlin, you can create the following String method extension:

fun String.toDate(): Date{
   return SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).parse(this)
}

Then you can sort the user's list by ascending date by doing:

users.sortedBy { it.enrolled_at.toDate() }
Sign up to request clarification or add additional context in comments.

1 Comment

Consider not using SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Consider java.time, the modern Java date and time API. If for API levels under 26, then either through desuraing or through the backport, ThreeTenABP.

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.