0Day Forums
Sort list with string date [Kotlin] - Printable Version

+- 0Day Forums (https://zeroday.vip)
+-- Forum: Coding (https://zeroday.vip/Forum-Coding)
+--- Forum: Kotlin (https://zeroday.vip/Forum-Kotlin)
+--- Thread: Sort list with string date [Kotlin] (/Thread-Sort-list-with-string-date-Kotlin)



Sort list with string date [Kotlin] - craniologist299770 - 07-20-2023

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...


RE: Sort list with string date [Kotlin] - bettejnyfcdpo - 07-20-2023

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 }



RE: Sort list with string date [Kotlin] - lionism595750 - 07-20-2023

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.




RE: Sort list with string date [Kotlin] - refluxing454967 - 07-20-2023

If you have a list of `String`s 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*


RE: Sort list with string date [Kotlin] - ronahljwttfumm - 07-20-2023

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

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


RE: Sort list with string date [Kotlin] - vanettavang997 - 07-20-2023


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.