在检查 Java 8 Optional 是否存在时,我如何 return 一个值?
How can I return a value while checking if a Java 8 Optional is present?
如何 return 一个值,但确保检查 .get() 有效?
假设 date
是一个 Optional<String>
。
methodThatTakesStringParam(date.ifPresent(s->s.get().replace("-", ""))) );
如果我只是使用它并执行 .get,如果它不存在,它就会抛出!
methodThatTakesStringParam( date.get().replace("-", "") );
我该如何处理?我看到的所有示例都类似于
date.ifPresent(System.out.println("showing that you can print to io is useless to me =)")
但在这种情况下我想 return 一个字符串——如果 .ifPresent() 为假,则为空字符串。
听起来你想要的是:
methodThatTakesStringParam(date.map(s->s.replace("-", ""))).orElse(""));
(参见the Javadoc for Optional<U>.map(Function<? super T,? extends U>)
。date.map(s->s.replace("-", ""))
大致相当于date.isPresent() ? Optional.of(date.get().replace("-", "")) : Optional.empty()
。)
编辑添加:也就是说,在这种特定情况下,写起来可能更简单:
methodThatTakesStringParam(date.orElse("").replace("-",""));
因为 "".replace("-","")
无论如何都会给出 ""
。
如何 return 一个值,但确保检查 .get() 有效?
假设 date
是一个 Optional<String>
。
methodThatTakesStringParam(date.ifPresent(s->s.get().replace("-", ""))) );
如果我只是使用它并执行 .get,如果它不存在,它就会抛出!
methodThatTakesStringParam( date.get().replace("-", "") );
我该如何处理?我看到的所有示例都类似于
date.ifPresent(System.out.println("showing that you can print to io is useless to me =)")
但在这种情况下我想 return 一个字符串——如果 .ifPresent() 为假,则为空字符串。
听起来你想要的是:
methodThatTakesStringParam(date.map(s->s.replace("-", ""))).orElse(""));
(参见the Javadoc for Optional<U>.map(Function<? super T,? extends U>)
。date.map(s->s.replace("-", ""))
大致相当于date.isPresent() ? Optional.of(date.get().replace("-", "")) : Optional.empty()
。)
编辑添加:也就是说,在这种特定情况下,写起来可能更简单:
methodThatTakesStringParam(date.orElse("").replace("-",""));
因为 "".replace("-","")
无论如何都会给出 ""
。