-2
我目前正在将可空字符串解析为日期。我尝试使用可选来避免使用if语句。以下是我迄今写:在Java 8中转换可选字符串并返回日期?
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);
}
});
是否有可能将这一拉姆达所以我可以把它类似于以下但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;
}