Java8-Optional类
笔记参考资料:https://www.bilibili.com/video/BV184411x7XA?p=21&spm_id_from=pageDriver
Optional类介绍
Optional类(java.util.Optional) 是-一个容器类,它可以保存类型T的值,代表这个值存在。或者仅仅保存null,,表示这个值不存在。原来用null表示一个值不存在,现在Optional可以更好的表达这个概念。并且可以避免空指针异常。
-
创建Optional 类对象的方法:
-
Optional.of(T t) :创建一个Optional实例,t必须非空; -
Optional.empty() :创建一个空的Optional实例 -
Optional.ofNullable(T t): 可以为null -
判断Optional容器中是否包含对象:
- boolean isPresent() :判断是否包含对象
- void ifPresent(Consumer<? super T> consumer) :如果有值,就执行Consumer
接口的实现代码,并且该值会作为参数传给它。 -
获取Optional容器的对象:
- T get():如果调用对象包含值,返回该值,否则抛异常
- T orElse(T other) :如果有值则将其返回,否则返回指定的other对象。
- T orElseGet(Supplier<? extends T> other) :如果有值则将其返回,否则返回由
Supplier接口实现提供的对象。 - T orElse Throw(Supplier<? extends X> exceptionSupplier) :如果有值则将其返
回,否则抛出由Supplier接口实现提供的异常。
创建Boy类
public class Boy {
public Boy() {
}
public Girl getGirl() {
return girl;
}
public void setGirl(Girl girl) {
this.girl = girl;
}
@Override
public String toString() {
return "Boy{" +
"girl=" + girl +
'}';
}
public Boy(Girl girl) {
this.girl = girl;
}
private Girl girl;
}
创建Girl类
public class Girl {
private String name;
public String getName() {
return name;
}
@Override
public String toString() {
return "Girl{" +
"name='" + name + '\'' +
'}';
}
public Girl() {
this.name = name;
}
public Girl(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
}
测试类
import org.junit.Test;
import java.util.Optional;
public class OptionalTest {
@Test
public void test1(){
Girl girl = new Girl();
Optional<Girl> optionalGirl = Optional.of(girl);
}
@Test
public void test2(){
Girl girl = new Girl();
girl = null;
Optional<Girl> optionalGirl = Optional.ofNullable(girl);
System.out.println(optionalGirl);
Girl girl1 = optionalGirl.orElse(new Girl("小丽"));
System.out.println(girl1);
}
public String getGirlName(Boy boy){
return boy.getGirl().getName();
}
@Test
public void test3(){
Boy boy = new Boy();
String girlName = getGirlName(boy);
System.out.println(girlName);
}
public String getGirlNamePlus(Boy boy){
if (boy!=null){
Girl girl = boy.getGirl();
if (girl!=null){
return girl.getName();
}
}
return null;
}
@Test
public void test4(){
Boy boy = new Boy();
String girlName = getGirlNamePlus(boy);
System.out.println(girlName);
}
public String getGirlNameOptional(Boy boy){
Optional<Boy> boyOptional = Optional.ofNullable(boy);
Boy boy1 = boyOptional.orElse(new Boy(new Girl("小红")));
Girl girl = boy1.getGirl();
Optional<Girl> girlOptional = Optional.ofNullable(girl);
Girl girl1 = girlOptional.orElse(new Girl("小美"));
return girl1.getName();
}
@Test
public void test5(){
Boy boy = null;
String girlName = getGirlNameOptional(boy);
System.out.println(girlName);
}
@Test
public void test6(){
Boy boy = null;
boy = new Boy();
String girlName = getGirlNameOptional(boy);
System.out.println(girlName);
}
}
|