package com.java1;
public class Girl {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Girl() {}
public Girl(String name) {
this.name = name;
}
@Override
public String toString() {
return "Girl{" + "name='" + name + '\'' + '}';
}
}
package com.java1;
public class Boy {
private Girl girl;
public Girl getGirl() {
return girl;
}
public void setGirl(Girl girl) {
this.girl = girl;
}
@Override
public String toString() {
return "Boy{" + "girl=" + girl + '}';
}
public Boy() {}
public Boy(Girl girl) {
this.girl = girl;
}
}
package com.java1;
import java.util.Optional;
import org.junit.Test;
public class OptionalTest {
@Test
public void test1() {
Girl girl = new Girl();
Optional<Girl> girl1 = 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();
boy = null;
String girlName = getGirlName(boy);
System.out.println(girlName);
}
public String getGirlName1(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();
boy = null;
String girlName = getGirlName1(boy);
System.out.println(girlName);
}
public String getGirlName2(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;
boy = new Boy();
boy = new Boy(new Girl("苍老师"));
String girlName = getGirlName2(boy);
System.out.println(girlName);
}
@Test
public void test6() {
Optional<Object> op1 = Optional.empty();
if (!op1.isPresent()) {
System.out.println("数据为空");
}
System.out.println(op1);
System.out.println(op1.isPresent());
}
@Test
public void test7() {
String str = "hello";
Optional<String> op1 = Optional.of(str);
String str1 = op1.get();
System.out.println(str1);
}
@Test
public void test8() {
String str = "beijing";
str = null;
Optional<String> op1 = Optional.ofNullable(str);
String str2 = op1.orElse("shanghai");
System.out.println(str2);
}
}