Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:
Sorting List with String Dates in Kotlin
Last updated: April 14, 2024
1. Overview
There are some scenarios where we need to store date values within a List to perform validations or make further processing. One common problem to solve during processing is sorting the data in a specific order.
In this tutorial, we’ll explore some approaches to sort a list of String dates in Kotlin.
2. Implementation
2.1. Using SimpleDateFormat
One approach to sorting string dates is to parse them into Date objects using SimpleDateFormat, then compare the Date objects and sort the list accordingly:
fun sortDatesDescending(dates: List<String>): List<String> {
val dateFormat = SimpleDateFormat("dd-MM-yyyy")
return dates.sortedByDescending { dateFormat.parse(it) }
}
2.2. Using LocalDate
Another approach is to use the LocalDate class from the java.time package, which provides a more modern and concise way to work with dates:
fun sortDatesDescending(dates: List<String>): List<String> {
val dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
return dates.sortedByDescending { LocalDate.parse(it, dateFormatter) }
}
2.3. Using Custom Comparator
We can also use a custom Comparator to compare and sort the string dates directly without converting them to Date objects or LocalDate instances:
fun sortDatesDescending(dates: List<String>): List<String> {
return dates.sortedWith(compareByDescending {
val (day, month, year) = it.split("-")
"$year-$month-$day"
})
}
3. Conclusion
In this article, we explored different approaches to sorting a list of string dates in descending order using Kotlin. Whether you prefer using SimpleDateFormat, LocalDate, or a custom Comparator, Kotlin provides flexible and concise syntax to accomplish this task efficiently.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.