Optional.get() 与重载 Optional.orElseThrow()
如何避免显式抛出一个尝试从或同时使用 Optional.get
获取值的时间?Exception
Optional
目前,这可能通过API进行保护,如下所示:orElseThrow
// exception could be replaced with any other
Integer opt = anyOddInStream.orElseThrow(
() -> new NoSuchElementException("No value present"));
然而,直接实现失望(当一个人可能不愿意明确地抛出一个异常时),同时试图访问类似的东西get
// the following not only just fails but throws an exception as well
Integer previous = anyOddInStream.get();
如果有人想确保任何一个都有一个值,如果没有,他们就不想继续向前传播,该怎么办?Optional
null