Joker
Joker

Reputation: 856

Sort list with string date [Kotlin]

I have arraylist typeBeanArrayList where element is some like a date: for example:

[30-03-2012, 28-03-2013, 31-03-2012, 2-04-2012, ...]

How can I sort in descending order.

Code:

typeBeanArrayList = database.getSingleCustomerDetail(c_id!!) //get data from SQlite database

creditListAdapter = CreditListAdapter(typeBeanArrayList)
rv_credit_list!!.adapter = creditListAdapter //Bind data in adapter

Thanks in advance...

Upvotes: 18

Views: 34123

Answers (5)

Abdulmoiz Esmail
Abdulmoiz Esmail

Reputation: 435

data class YouModel(val startDate: String? = null) {

  val BY_DATE_ORDER =
            compareByDescending<YourModel> {
                val format = SimpleDateFormat("yyyy-MM-dd")
                var convertedDate = Date()
                try {
                    convertedDate = it.startDate?.let { it1 -> format.parse(it1) } as Date
                } catch (e: ParseException) {
                    e.printStackTrace()
                }

                convertedDate
            }
    }



yourList<YourModel>?.sortedWith(YourModel.BY_DATE_ORDER)

This works for me. I created a descending comparator using the function to transform value to a Comparable instance for comparison. I converted the string date to date before applying the sorting function.

Upvotes: 0

You can use something like this if you are using a custom model

typeBeanArrayList.sortedWith(compareByDescending<YourModel> { it.date() })

Upvotes: 3

user2340612
user2340612

Reputation: 10723

If you have a list of Strings representing dates, one way to sort them in descending order is:

val dates = listOf("30-03-2012", "28-03-2013", "31-03-2012", "2-04-2012")

val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")

val result = dates.sortedByDescending {
    LocalDate.parse(it, dateTimeFormatter)
}

println(result)

This will print:

[28-03-2013, 2-04-2012, 31-03-2012, 30-03-2012]

Note that sortedByXXX methods return a new List, i.e., they don't sort in place

Upvotes: 12

Joker
Joker

Reputation: 856

Thank you @svkaka for information.

I just notice one line from @svkaka answer : .sortByDescending { it.length }.

and i changes in my code like :

typeBeanArrayList.sortByDescending{it.date}

Sorting is perfectly work.

Upvotes: 36

svkaka
svkaka

Reputation: 4032

Use

[30-03-2012, 28-03-2013, 31-03-2012, 2-04-2012, ...].sortDescending()

if you want to sort by param use in this case length

[30-03-2012, 28-03-2013, 31-03-2012, 2-04-2012, ...].sortByDescending { it.length }

Upvotes: 3

Related Questions