Kotlin - Sort List by using formatted date string (functional)

Another alternative to the excellent Saravana answer (for minimalist and compact freaks like me..) is:

val cmp = compareBy<String> { LocalDateTime.parse(it, DateTimeFormatter.ofPattern("dd-MM-yyyy | HH:mm")) }

list.sortedWith(cmp).forEach(::println)

01-08-2015 | 09:29
14-10-2016 | 15:48
15-11-2016 | 19:43

Ps: it is the default variable for single inputs


More than one approach can be used. It depends on how you process after you get the sorted result.

Points to note:

  • java.time.LocalDateTime has already implemented java.lang.Comparable<T> Interface. We can use the kotlin stdlib List.sortBy to sort the List<LocalDateTime> directly.

Ref:

// https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sorted-by.html
fun <T, R : Comparable<R>> Iterable<T>.sortedBy(
    selector: (T) -> R?
): List<T>

The easiest way is to transform the String -> java.time.LocalDateTime and use the List.sortBy directly.

The whole implementation could be like this:

 import java.time.LocalDateTime
 import java.time.format.DateTimeFormatter

 ...


// Create a convert function, String -> LocalDateTime
val dateTimeStrToLocalDateTime: (String) -> LocalDateTime = {
    LocalDateTime.parse(it, DateTimeFormatter.ofPattern("dd-MM-yyyy | HH:mm"))
}

val list = listOf("14-10-2016 | 15:48",
        "01-08-2015 | 09:29",
        "15-11-2016 | 19:43")

// You will get List<LocalDateTime> sorted in ascending order
list.map(dateTimeStrToLocalDateTime).sorted()

// You will get List<LocalDateTime> sorted in descending order
list.map(dateTimeStrToLocalDateTime).sortedDescending()

// You will get List<String> which is sorted in ascending order
list.sortedBy(dateTimeStrToLocalDateTime)

// You will get List<String> which is sorted in descending order
list.sortedByDescending(dateTimeStrToLocalDateTime)

If you want to use org.joda.time.DateTime, you can just make a tiny change on the convert function.

A friendly reminder, always pick val as your first choice in Kotlin :).