来自比较器的未处理异常类型 ParseException

Unhandled exception type ParseException from comparator

我需要对代表 日期 String 列表进行排序。

我尝试了以下代码:

try {
    SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
    Collections.sort(days,
            (s1, s2) -> sdf.parse(s1).compareTo(sdf.parse(s2)));
} catch (ParseException e) {
    e.printStackTrace();
}

但在 Eclipse 中,我在 sdf.parse(s1):

处遇到编译时错误

Unhandled exception type ParseException

有什么解决办法吗?

我的输入列表是:

[2016-01-02, 2016-01-03, 2016-01-01]

SimpleDateFormat::parse method throws a checked exception,因此您必须在调用方法的地方捕获它 - 在本例中,在 lambda 表达式中。

另一个问题是大写 Y 而不是 代表年份。 Check the javadoc: Y is the week year field,这并不总是与年份相同。您必须将其更改为小写 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?
});

但是此代码存在问题:如果出现 ParseException,则意味着 String 不包含预期格式的日期 (yyyy-MM-dd)。在这种情况下你应该怎么做?忽略它和上面的return 0(意思是invalid string is "equal" to any date?)。停止排序并抛出异常?

也许最好先尝试将字符串转换为日期(如果发现无效字符串,您可以决定忽略或停止转换),然后,当您确定所有元素是有效日期,您对它们进行排序。

Java date/time API

由于您使用的是 lambda,您的 Java 版本是 >= 8,那么为什么不使用 new date/time API

假设 daysString 的集合:

List<LocalDate> sortedDates = days.stream()
    // parse to LocalDate
    .map(LocalDate::parse)
    // sort
    .sorted()
    // get list of LocalDate's
    .collect(Collectors.toList());

在这种情况下,days 中任何无效的 String 都会使这段代码抛出异常,并且排序不会完成。不同之处在于此方法抛出一个 unchecked 异常,因此您无需像在 SimpleDateFormat.

中那样在此处显式捕获它

如果您想要对 days 列表进行排序,只需将 LocalDate 转换回 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());