Search code examples
kotlinarraylistzoneddatetime

How to sort arraylist of ZonedDateTime in Kotlin?


I am trying to create a messaging app in Android and I need to sort the messages according to their timestamps, which I created from a ZonedDateTime object. I was going to parse the timestamp strings with the formatter I used to re-create a ZonedDateTime object, but I need to be able to sort the arraylist of ZonedDateTime objects in chronological order. How can I do this?


Solution

  • sorted() is the way to sort items in a list.

    sort() will sort a mutable list or array.

    In the Kotlin documentation, there are allusions to sorting by a natural order which only means that the class needs to implement the Comparable interface. ZonedDateTime implements ChronoZonedDateTime which implements Comparable so these methods should work.