Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list with string date [Kotlin]

Tags:

sorting

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

like image 691
Joker Avatar asked Feb 28 '19 12:02

Joker


2 Answers

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.

like image 76
Joker Avatar answered Sep 18 '22 18:09

Joker


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

like image 32
user2340612 Avatar answered Sep 18 '22 18:09

user2340612