Search code examples
kotlindatedatetimetimezoneddatetime

Descending order ZoneDateTime in list kotlin


I have list of ZoneDateTime. I want to order by descending order. I didn't find the solution. Can some one guide me.

NearestResult(day=2020-05-09T20:09:03+01:00, event=xyz)
NearestResult(day=2020-05-09T09:15:15+01:00, event=abc)
NearestResult(day=2020-05-09T23:15:15+01:00, event=qwe)
NearestResult(day=2020-05-09T14:00:40+01:00, event=aks)

NearestResult.kt

data class NearestResult(
    val day: ZonedDateTime,
    val event: String
)

I tried some code but it's not working

lis.groupBy { it.day }

It giving me same above order.

Expected Output

NearestResult(day=2020-05-09T23:15:15+01:00, event=qwe)
NearestResult(day=2020-05-09T20:09:03+01:00, event=xyz)
NearestResult(day=2020-05-09T14:00:40+01:00, event=aks)
NearestResult(day=2020-05-09T09:15:15+01:00, event=abc)

Can somone guide me. Many Thanks


Solution

  • val desc = compareByDescending<NearestResult>{
       it.day
    }
    val asc = compareBy<NearestResult>{
       it.day
    }
       
    val sortedList = list.sortedWith(desc)
    println(sortedList)
    
    //or
    
    list.sortedByDescending{ it.day }