Optional 是个好东西,你真的会用么?
阅读本文大概需要 6 分钟。
引言
user.getAddress().getProvince();
if(user!=null){
Address address = user.getAddress();
if(address!=null){
String province = address.getProvince();
}
}
API介绍
Optional(T value),empty(),of(T value),ofNullable(T value)
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
通过of(T value)函数所构造出的Optional对象,当Value值为空时,依然会报NullPointerException。 通过of(T value)函数所构造出的Optional对象,当Value值不为空时,能正常构造Optional对象。
public final class Optional<T> {
//省略....
private static final Optional<?> EMPTY = new Optional<>();
private Optional() {
this.value = null;
}
//省略...
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
}
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
orElse(T other),orElseGet(Supplier<? extends T> other)和orElseThrow(Supplier<? extends X> exceptionSupplier)
@Test
public void test() {
User user = null;
user = Optional.ofNullable(user).orElse(createUser());
user = Optional.ofNullable(user).orElseGet(() -> createUser());
}
public User createUser(){
User user = new User();
user.setName("zhangsan");
return user;
}
User user = null;
Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));
map(Function<? super T, ? extends U> mapper)和flatMap(Function<? super T, Optional<U>> mapper)
public final class Optional<T> {
//省略....
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
//省略...
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
}
Function<? super T, ? extends U>
,而flapMap的入参类型为Function<? super T, Optional<U>>
。public class User {
private String name;
public String getName() {
return name;
}
}
String city = Optional.ofNullable(user).map(u-> u.getName()).get();
public class User {
private String name;
public Optional<String> getName() {
return Optional.ofNullable(name);
}
}
String city = Optional.ofNullable(user).flatMap(u-> u.getName()).get();
isPresent()
和ifPresent(Consumer<? super T> consumer)
public final class Optional<T> {
//省略....
public boolean isPresent() {
return value != null;
}
//省略...
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
}
if (user != null){
// TODO: do something
}
User user = Optional.ofNullable(user);
if (Optional.isPresent()){
// TODO: do something
}
ifPresent(Consumer<? super T> consumer)
,用法也很简单,如下所示Optional.ofNullable(user).ifPresent(u->{
// TODO: do something
});
filter(Predicate<? super T> predicate)
public final class Optional<T> {
//省略....
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
Optional<User> user1 = Optional.ofNullable(user).filter(u -> u.getName().length()<6);
实战使用
public String getCity(User user) throws Exception{
if(user!=null){
if(user.getAddress()!=null){
Address address = user.getAddress();
if(address.getCity()!=null){
return address.getCity();
}
}
}
throw new Excpetion("取值错误");
}
public String getCity(User user) throws Exception{
return Optional.ofNullable(user)
.map(u-> u.getAddress())
.map(a->a.getCity())
.orElseThrow(()->new Exception("取指错误"));
}
if(user!=null){
dosomething(user);
}
Optional.ofNullable(user)
.ifPresent(u->{
dosomething(u);
});
public User getUser(User user) throws Exception{
if(user!=null){
String name = user.getName();
if("zhangsan".equals(name)){
return user;
}
}else{
user = new User();
user.setName("zhangsan");
return user;
}
}
public User getUser(User user) {
return Optional.ofNullable(user)
.filter(u->"zhangsan".equals(u.getName()))
.orElseGet(()-> {
User user1 = new User();
user1.setName("zhangsan");
return user1;
});
}
推荐阅读:
IDEA 的 debug 怎么实现?出于这个好奇心,我越挖越深!
最近面试BAT,整理一份面试资料《Java面试BATJ通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
朕已阅