【发布时间】:2016-11-16 14:42:08
【问题描述】:
我目前正在将一个可为空的字符串解析为一个日期。我尝试使用 Optional 来避免使用 if 语句。这是我到目前为止所写的:
Client client = new Client();
Optional.ofNullable(methodThatMayReturnStringOrNull())
.ifPresent((s) -> {
try {
client.setBirthDate(DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
是否可以转换此 lambda,以便我可以使其成为类似于以下但 java 8 样式的方法?
private Date parse(String complexString) {
Date birthDate = null;
if (complexString != null) {
try {
birthDate = DateUtils.parseDate(
StringUtils.substring(complexString, 0, 10),
new String[]{"yyyy-MM-dd"});
} catch (final ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
}
return birthDate;
}
【问题讨论】: