简体   繁体   中英

How to sort array of times with AM and PM at the end in descending order in Java

I Have an array list as below

 {"8:00 am", "8:32 am", "8:10 am", "1:00 pm", "3:00 pm", "2:00 pm"}

I tried using Collections sort but I couldn't get the desired output I need to get the output sorted as below

{3:00 pm, 2:00 pm, 1:00 pm, 8:32 am, 8:10 am, 8:00 am}

Parse the string into LocalTime by using DateTimeFormatter in Comparator so that it sorts the array based on time

Arrays.sort(time, Comparator.comparing(str->LocalTime.parse(str.toUpperCase(),DateTimeFormatter.ofPattern("h:mm a"))));

If you want descending order you can simply use reverse Comparator

Comparator.comparing((String str)->LocalTime.parse(str.toUpperCase(),DateTimeFormatter.ofPattern("h:mm a"))).reversed()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM