Like others I recommend not reinventing the wheel, and I also recommend discarding the old and outdated classes SimpleDateFormat
and Date
. We have so much better these days.
Given
static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
we can do
Collections.sort(listOfTimeStrings,
Comparator.comparing(
(String s) -> LocalTime.parse(s.toUpperCase(), dtf)));
This will work nicely for a few hundred strings, maybe more. It will, however, parse each string each time two strings are to be compared. That could be many times. If you want to parse each string only once, instead do:
List<String> sortedList = listOfTimeStrings.stream()
.map(String::toUpperCase)
.map(s -> LocalTime.parse(s, dtf))
.sorted()
.map(dtf::format)
.map(String::toLowerCase)
.collect(Collectors.toList());
I have taken it literally when you give am and pm in lowercase, so I am converting to uppercase before the parsing and back to lowercase after formatting. Depending on your data you may skip these steps.