Optional对象的用法
Optional(T value),empty(),of(T value),ofNullable(T value)
of()方法的源码:
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
通过of(T value)函数所构造出的Optional对象,当Value值为空时,会报NullPointerException异常。
通过of(T value)函数所构造出的Optional对象,当Value值不为空时,能正常构造Optional对象,并返回这个对象。
empty()方法的源码:
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;
}
empty()的作用就是返回EMPTY对象
ofNullable(T value)方法的源码:
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
相比较of(T value)的区别就是,当value值为null时,of(T value)会报NullPointerException异常;
ofNullable(T value)不会throw Exception,ofNullable(T value)直接返回一个EMPTY对象。
orElse(T other),orElseGet(Supplier other)和orElseThrow(Supplier exceptionSupplier)
这三组方法 都是在构造函数传入的value值为null时,进行调用的。
@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;
}
@Test
public User orElseThrow(){
User user = null;
Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));
}
orElse和orElseGet的用法:相当于value值为null时,给予一个默认值。
这两个函数的区别:当user值不为null时,orElse函数依然会执行createUser()方法,而orElseGet函数并不会执行createUser()方法
orElseThrow:当value值为null时,直接抛一个异常出去
map(Function mapper)和flatMap(Function> mapper)
这两个函数做的是转换值的操作
map和flatMap的源码:
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));
}
}
map函数所接受的入参类型为Function<? super T, ? extends U>,
而flapMap的入参类型为Function<? super T, Optional>。
isPresent()和ifPresent(Consumer consumer)
isPresent即判断value值是否为空,而ifPresent就是在value值不为空时
源码如下:
public boolean isPresent() {
return value != null;
}
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
用法:
// isPresent 相当于
if(user == null){}
// 用法
Optional.ofNullable(user).isPresent(u->{
// TODO: user等于空时 do something
});
// ifPresent 相当于
if(user != null){}
// 用法
Optional.ofNullable(user).ifPresent(u->{
// TODO: user不为空时 do something
});
filter(Predicate predicate) 源码如下:
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
filter 方法接受一个 Predicate 来对 Optional 中包含的值进行过滤,
如果包含的值满足条件返回Optional对象,否则返回 Optional.empty。
用法:过滤名字长度小于6的数据
Optional<User> user1 = Optional.ofNullable(user).filter(u -> u.getName().length()<6);
如果user的name的长度是小于6的,则返回。如果是大于6的,则返回一个EMPTY对象。
示例:
// 以前得到写法
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("取值错误");
}
// 使用java8的 Optional 写法
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);
}
// 使用java8的 Optional 写法
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;
}
}
// 使用java8的 Optional 写法
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;
});
}