我如何返回一个值,但确保检查 .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 =)")
但在这种情况下我想返回一个字符串——如果 .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("-","")
给出 ""
无论如何。
关于java - 如何在检查是否存在 Java 8 Optional 时返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28921487/