2016-11-16 50 views
-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; 
} 

回答

0

不知道你要能走多远,但你可以

Optional<Date> date = Optional.ofNullable(methodThatMayReturnStringOrNull()) 
.map((s) -> { 
    try { 
    return DateUtils.parseDate(
     StringUtils.substring(s, 0, 10), 
     new String[]{"yyyy-MM-dd"})); 
    } catch (ParseException e) { 
     throw new TechnicalException("error.parsing.date", e); 
    } 
}); 

开始,您还可以考虑使用flatMap代替map和返回空可选,而不是在错误引发异常 - 取决于你想如何推进你的流程。

在完全无关的笔记上,摆脱Date并使用joda或新的java时间类;)