楼上回答了那么多,其实 guava 文档里就有解释。
Besides the increase in readability that comes from giving null a name (增加了可读性,isPresent()比 if xxx!=null 可读性好)
the biggest advantage of Optional is its
idiot-proof-ness.It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case (使用了 option 后,强迫你思考不存在的情况,避免忘记)
This is especially relevant when you're returning values that may or may not be "present." You (and others) are far more likely to forget that other.method(a, b) could return a null value than you're likely to forget that a could be null when you're implementing other.method. Returning Optional makes it impossible for callers to forget that case, since they have to unwrap the object themselves for their code to compile.
(对设计的优化,如果你的方法返回值可能存在也可能不存在,就尽量返回 optional,这样别人用你的方法就知道需要判断)
至于 orElse 这种类型操作,我自己理解的是 4 楼那样,此外,optional 并不是用来简化流程,只是一种设计,让人记住去处理 null