Search code examples
androidsortingkotlinandroid-date

Efficient way to sort dates with their values in a JSON Array in Kotlin


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.


Solution

  • 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() }