It is possible to sort the strings as they are using a custom comparator as haaawk mentioned in a a comment (and probably soon in the answer). This would mean parsing the strings each time two are compared, which could be a noticeable waste if you have very many of them. Instead I suggest a custom class containing the string and a parsed date-time.
public class StringWithDateTime implements Comparable<StringWithDateTime> {
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("dd/M/uuuu HH:mm");
private String dateTimeAndInt;
/**
* (Premature?) optimization: the dateTime from the string
* to avoid parsing over and over
*/
private LocalDateTime dateTime;
public StringWithDateTime(String dateTimeAndInt) {
this.dateTimeAndInt = dateTimeAndInt;
// parse the date-time from the beginning of the string
dateTime = LocalDateTime.from(
FORMATTER.parse(dateTimeAndInt, new ParsePosition(0)));
}
@Override
public int compareTo(StringWithDateTime other) {
return dateTime.compareTo(other.dateTime);
}
@Override
public String toString() {
return dateTimeAndInt;
}
}
With this class you can do for example
List<StringWithDateTime> listWithDateTimes = Arrays.asList(
new StringWithDateTime("02/08/2017 13:00 198"),
new StringWithDateTime("02/7/2018 08:00 75"),
new StringWithDateTime("04/12/2014 19:00 5")
);
Collections.sort(listWithDateTimes);
listWithDateTimes.forEach(System.out::println);
The output of the snippet is the original strings in chronological order:
04/12/2014 19:00 5
02/08/2017 13:00 198
02/7/2018 08:00 75
Go ahead and sort many more strings this way.
With DateTimeFormatter
, while MM
in the format pattern string would have required 2-digit months throughout, one M
will match both 1-digit and 2-digit months as in the different variants of your format.
java.time
Question: you are using java.time
, the modern Java date and time API — does this work on my Android device?
It will. The new API is known as JSR-310. To use it on Android, get ThreeTenABP the Android backport of JSR-310 (from Java 8). More explanation in this question: How to use ThreeTenABP in Android Project.
For anyone reading along (and programming for something else than Android), java.time
is built into Java 8 and later. You can use it in Java 6 and 7 through ThreeTen Backport.
Question; Why an external library? Doesn’t Android come with SimpleDateFormat
built in?
The modern API is so much nicer to work with, and SimpleDateFormat
in particular is notoriously troublesome. Instead I recommend you start using the future-proof API today.