SimpleDateFormat::parse
method throws a checked exception, so you must catch it where the method is called - in this case, inside the lambda expression.
Another problem is that uppercase Y
does not represent the year. Check the javadoc: Y
is the week year field, which is not always the same as the year. You must change it to lowercase y
:
// use lowercase "y" for year
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Collections.sort(days, (s1, s2) -> {
try {
return sdf.parse(s1).compareTo(sdf.parse(s2));
} catch (ParseException e) {
// what to do when parse fails? just ignore and go on? throw exception?
}
return 0; // return something or throw exception?
});
But there are problems with this code: if a ParseException
occurs, it means the String
doesn't contain a date in the expected format (yyyy-MM-dd
). What should you do in this case? Ignore it and return 0 as above (meaning that the invalid string is "equal" to any date?). Stop the sorting and throw an exception?
Maybe it's better to first try to convert the strings to dates (and if you find an invalid string, you can decide to either ignore or stop the conversion), and just after that, when you're sure all elements are valid dates, you sort them.
Java date/time API
As you're using lambdas, your Java version is >= 8, so why not use the new date/time API?
Assuming that days
is a collection of String
's:
List<LocalDate> sortedDates = days.stream()
// parse to LocalDate
.map(LocalDate::parse)
// sort
.sorted()
// get list of LocalDate's
.collect(Collectors.toList());
In this case, any invalid String
in days
will make this code throw an exception and the sorting won't be done. The difference is that this method throws an unchecked exception, so you don't need to explicity catch it here, as you did with SimpleDateFormat
.
If you want the days
list sorted, though, just convert the LocalDate
back to String
:
days = days.stream()
// parse to LocalDate
.map(LocalDate::parse)
// sort
.sorted()
// convert back to string
.map(LocalDate::toString)
// get list of String's
.collect(Collectors.toList());