这时候取 name 的写法如下所示
String city = Optional.ofNullable(user).map(u-> u.getName()).get();
对于 flatMap 而言:
如果 User 结构是下面这样的
public class User {
private String name;
public Optional getName() {
return Optional.ofNullable(name);
}
}
这时候取 name 的写法如下所示
String city = Optional.ofNullable(user).flatMap(u-> u.getName()).get();
4、isPresent() 和 ifPresent(Consumer<? super T> consumer)
这两个函数放在一起记忆,isPresent
即判断 value 值是否为空,而ifPresent
就是在 value 值不为空时,做一些操作。这两个函数的源码如下
public final class Optional {
//省略…
public boolean isPresent() {
return value != null;
}
//省略…
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
}
需要额外说明的是,大家千万不要把