Java8新特性4:Optional
1 Optional介绍
Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
Optional 类的引入很好的解决空指针异常。
package com.yppah.myOptional.p1;
/**
* @Author: haifei
* @Date: 2022/10/28 9:53
*/
public class Order {
private String orderId;
private String orderName;
private String orderDes;
public Order(String orderId, String orderName) {
this.orderId = orderId;
this.orderName = orderName;
}
public String getOrderId() {
return orderId;
}
public String getOrderName() {
return orderName;
}
public String getOrderDes() {
return orderDes;
}
}
package com.yppah.myOptional.p1;
import com.sun.org.apache.xpath.internal.operations.Or;
import java.util.Optional;
/**
* @Author: haifei
* @Date: 2022/10/28 9:15
*/
public class Test01 {
private static Order order;
public static void main(String[] args) {
Order order = getOrder();
System.out.println(order); //com.yppah.myOptional.p1.Order@816f27d
}
public static Order getOrder(){
/*if (order == null){
return createOrder();
}*/
order = Optional.ofNullable(order)
.orElseGet(()->createOrder());
return order;
}
public static Order createOrder() {
return new Order("1234", "irun2u");
}
}
package com.yppah.myOptional.p1;
import java.util.Optional;
/**
* @Author: haifei
* @Date: 2022/10/28 10:11
*/
public class Test02 {
public static void main(String[] args) {
System.out.println(Test02.getOrderName()); //irun2u
}
public static String getOrderName() {
Order order = new Order("1234", "irun2u");
//优化前写法:
/*if (order != null) {
String orderName = order.getOrderName();
if (orderName != null) {
return orderName.toLowerCase();
}
}*/
//优化后写法:
return Optional.ofNullable(order)
.map(order2->order2.getOrderName())
.map(orderName->orderName.toLowerCase())
.orElse("df");
}
}
2 常用功能
2.1 判断参数是否为空
Optional.ofNullable(可以传递一个空对象)
Optional.of(不可以传递空对象)
isPresent():返回false表示值为空,返回true表示值不为空
package com.yppah.myOptional.p1;
import java.util.Optional;
/**
* @Author: haifei
* @Date: 2022/10/28 10:27
*/
public class Test03 {
public static void main(String[] args) {
String str1 = null;
String str2 = "irun2u";
Optional<String> optional = Optional.ofNullable(str1);
// System.out.println(optional.get()); //java.util.NoSuchElementException: No value present
boolean present = optional.isPresent();
System.out.println(present); //false
Optional<String> optional2 = Optional.ofNullable(str2);
System.out.println(optional2.get()); //irun2u
boolean present2 = optional2.isPresent();
System.out.println(present2); //true
// Optional<String> optional3 = Optional.of(str1); //java.lang.NullPointerException
// System.out.println(optional3.get());
Optional<String> optional4 = Optional.of(str2);
System.out.println(optional4.get()); //irun2u
/*
Optional.ofNullable(可以传递一个空对象)
Optional.of(不可以传递空对象)
*/
}
}
2.2 参数为空可以设定默认值
.orElse()
package com.yppah.myOptional.p1;
import java.util.Optional;
import java.util.function.Predicate;
/**
* @Author: haifei
* @Date: 2022/10/28 11:08
*/
public class Test04 {
public static void main(String[] args) {
String username = null;
String uName = Optional.ofNullable(username).orElse("irun2u");
System.out.println(uName); //username为空时指定默认值"irun2u"
}
}
2.3 参数实现过滤
.filter()
package com.yppah.myOptional.p1;
import java.util.Optional;
import java.util.function.Predicate;
/**
* @Author: haifei
* @Date: 2022/10/28 11:08
*/
public class Test04 {
public static void main(String[] args) {
String username = null;
/*boolean present = Optional.ofNullable(username).filter(new Predicate<String>() {
@Override
public boolean test(String s) {
return "iu".equals(s);
}
}).isPresent();*/
boolean present = Optional.ofNullable(username)
.filter(s -> "iu".equals(s))
.isPresent();
System.out.println(present); //false
}
}
3 结合Lambda优化代码
3.1 优化方案1
package com.yppah.myOptional.p2;
import java.util.Optional;
import java.util.function.Consumer;
/**
* @Author: haifei
* @Date: 2022/10/28 11:23
*/
public class Test05 {
public static void main(String[] args) {
String str1 = null;
String str2 = "irun2u";
Optional<String> optional = Optional.ofNullable(str2);
boolean present = optional.isPresent();
if (present) {
System.out.println(optional.get());
}
// str不为空时会直接调用accept();str==null时不执行accept()
/*optional.ifPresent(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});*/
// optional.ifPresent(s -> System.out.println(s));
//此处可以换用方法引入(参考昨天学习的规则)
optional.ifPresent(System.out::println);
}
}
3.2 优化方案2
package com.yppah.myOptional.p2;
import com.yppah.myOptional.p1.Order;
import java.util.Optional;
import java.util.function.Supplier;
/**
* @Author: haifei
* @Date: 2022/10/28 11:40
*/
public class Test06 {
private static Order order;
public static void main(String[] args) {
System.out.println(Test06.getOrder());
System.out.println(Test06.order);
/*
优化前:
com.yppah.myOptional.p1.Order@15db9742
com.yppah.myOptional.p1.Order@15db9742
优化1后:
com.yppah.myOptional.p1.Order@15db9742
null
优化2后:
com.yppah.myOptional.p1.Order@15db9742
com.yppah.myOptional.p1.Order@15db9742
*/
}
public static Order getOrder(){
/*if (order == null){
order = createOrder();
}
return order;*/
//优化1如下
// return Optional.ofNullable(order).orElse(createOrder());
//优化2如下
return Optional.ofNullable(order).orElseGet(new Supplier<Order>() {
@Override
public Order get() {
order = createOrder();
return order;
}
});
//.orElseGet():通过写函数接口的形式赋默认值
//.orElse():直接传递默认值
}
public static Order createOrder() {
return new Order("1234", "irun2u");
}
}
方法引入:
package com.yppah.myOptional.p2;
import com.yppah.myOptional.p1.Order;
import java.util.Optional;
import java.util.function.Supplier;
/**
* @Author: haifei
* @Date: 2022/10/28 11:40
*/
public class Test07 {
private static Order order;
public static void main(String[] args) {
System.out.println(Test07.getOrder());
System.out.println(Test07.order);
/*
com.yppah.myOptional.p1.Order@816f27d
com.yppah.myOptional.p1.Order@816f27d
*/
}
public static Order getOrder(){
return Optional.ofNullable(order).orElseGet(Test07::orElseGet);
}
public static Order createOrder() {
return new Order("1234", "irun2u");
}
public static Order orElseGet() {
order = createOrder();
return order;
}
}
3.3 优化方案3
package com.yppah.myOptional.p2;
import com.yppah.myOptional.p1.Order;
import java.util.Optional;
/**
* @Author: haifei
* @Date: 2022/10/28 13:59
*/
public class Test08 {
public static void main(String[] args) {
// 字符串中大写转小写
System.out.println(Test08.getOrderName()); //yjwyhf
}
public static String getOrderName() {
Order order = new Order("654321", "YjwYhf");
// 优化前:
/*if (order != null) {
String orderName = order.getOrderName();
if (orderName != null) {
return orderName.toLowerCase();
}
}
return null;*/
// 优化后:
/*Optional<Order> optional = Optional.ofNullable(order);
Optional<String> stringOptional = optional.map(order1 -> order1.getOrderName());
Optional<String> toLowerCase = stringOptional.map(name -> name.toLowerCase());
return toLowerCase.get();*/
// 简写如下
return Optional.ofNullable(order)
.map(order1 -> order1.getOrderName())
.map(orderName->orderName.toLowerCase())
.orElse(null);
}
}