package com.tonis.demo;
import com.tonis.demo.entity.User;
import java.util.Optional;
public class OptionalTest {
public static void main(String[] args) {
// Optional实例化 of/ofNullable
Optional emptyOpt = Optional.empty();
// throw java.lang.NullPointerException
//Optional ofOpt = Optional.of(null);
Optional ofNullOpt = Optional.ofNullable(null);
User user1 = null;
User user2 = new User(1,"Tom", 20);
// filter过滤值 map/flatmap转换值 同stream中对应操作
// isPresent get
/**
* get需在isPresent()方法返回true时再调用,否则会报异常,如下:
* java.util.NoSuchElementException: No value present
*/
User user = Optional.ofNullable(user1).get();
// ifPresent
Optional.ofNullable(user2).ifPresent(e->{
System.out.println(e.getName());
});
// orElse orElseGet 但对象为null时获取默人值
/**
* 当optional域中的值为空时,两者一样;当optional域中不为空时,orElse也会执行,orElseGet则不会
*/
/**
* out print:
* create ...
* create 2 ....
*/
Optional.ofNullable(user1).orElse(createUser());
Optional.ofNullable(user1).orElseGet(()->{
System.out.println("create 2 ....");
return null;
});
/**
* out print:
* create ...
*/
Optional.ofNullable(user2).orElse(createUser());
Optional.ofNullable(user2).orElseGet(()->{
System.out.println("create 2 ....");
return null;
});
/**
* optional项目中的使用: 链式调用
*/
String result = Optional.ofNullable(user)
.flatMap(u -> u.getAddress())
.flatMap(a -> a.getCountry())
.map(c -> c.getIsocode())
.orElse("default");
}
private static User createUser(){
System.out.println("create ...");
return null;
}
}
注:1、使用get前需使用isPresent检查
2、Optional 类型用作属性或是方法参数在 IntelliJ IDEA 中是强力不推荐的
Reports any uses of java.util.Optional<T>, java.util.OptionalDouble, java.util.OptionalInt, java.util.OptionalLong or com.google.common.base.Optional as the type for a field or a parameter. Optional was designed to provide a limited mechanism for library method return types where there needed to be a clear way to represent “no result”. Using a field with type java.util.Optional is also problematic if the class needs to be Serializable, which java.util.Optional is not. (使用任何像 Optional 的类型作为字段或方法参数都是不可取的. Optional 只设计为类库方法的, 可明确表示可能无值情况下的返回类型. Optional 类型不可被序列化, 用作字段类型会出问题的)