java8 Optional的使用,Optional实例,使你的代码高大上
程序员文章站
2022-06-07 09:56:31
...
java8 Optional的使用,Optional实例,使你的代码高大上
Optional是为了解决空指针异常,本质是一个包含可选值的包装类,或者说是一个容器
实例代码
package com.dume.boot.code;
import java.util.Optional;
/**
* @author dume
* @create 2021-09-13 10:53
*
* Optional是为了解决空指针异常,本质是一个包含可选值的包装类,或者说是一个容器
**/
public class OptionalDemo {
public static void main(String[] args) {
Student studentnull = null;
Student student = new Student("john1",11);
Student student2 = new Student("john2",22);
Student student3 = new Student("john3",33);
Student student4 = new Student("john4",44);
//isPresent判断值不为空,get返回对象
System.out.println("*******************isPresent判断值不为空,get返回对象**********************");
Optional<Student> optional = Optional.ofNullable(student);
if(optional.isPresent()){
Student back1 = optional.get();
System.out.println("back1:"+back1.toString());
}
System.out.println("*********************ifPresent判断不为空, 并执行Lambda 表达式********************");
//ifPresent判断不为空,Consumer(消费者) 参数,如果对象不是空的,就执行传入的 Lambda 表达式
//注意没有返回值
optional.ifPresent(u->ifFuction(u));
System.out.println("*********************orElse判断不为空,否则返回默认值********************");
//orElse判断不为空,否则返回默认值
Student back2 = Optional.ofNullable(studentnull).orElse(student2);
System.out.println("back2:"+back2.toString());
System.out.println("*******************orElseGet不为空时返回值;为空时作为参数传入函数式接口,并返回执行后的参数**********************");
//orElseGet不为空时返回值;为空时,他会作为参数传入Supplier(供应者) 函数式接口,并返回执行后的参数
Student back3 = Optional.ofNullable(studentnull).orElse(createStudent());
Student back4 = Optional.ofNullable(studentnull).orElseGet(()->createStudent());
System.out.println("back3:"+back3.toString());
System.out.println("back4:"+back4.toString());
/**
* 可见当都为空时,orElse与orElseGet并无差别
* 当都不为空时,orElse依然会执行,orElseGet不会执行。所以orElseGet效率更高
*/
System.out.println("*********************当都不为空时,orElse依然会执行,orElseGet不会执行********************");
Student back5 = Optional.ofNullable(student).orElse(createStudent());
Student back6 = Optional.ofNullable(student).orElseGet(()->createStudent());
System.out.println("back5:"+back5.toString());
System.out.println("back6:"+back6.toString());
//orElseThrow当为空时,抛出自定义异常
System.out.println("*********************orElseThrow当为空时,抛出自定义异常********************");
try {
Student back7 = Optional.ofNullable(studentnull).orElseThrow(()-> new IllegalArgumentException());
}catch (Exception e){
e.printStackTrace();
}
//map转换值,map() 对值调用作为参数的函数,然后将返回的值包装在 Optional
System.out.println("*********************map转换值********************");
String back8 = Optional.ofNullable(studentnull).map(u->u.getName()).orElse("DEFUAFT");
String back9 = Optional.ofNullable(studentnull).map(Student::getName).orElse("DEFUAFT");
System.out.println("back8:"+back8);
System.out.println("back9:"+back9);
//flatMap() 也需要函数作为参数,并对值调用这个函数,然后直接返回结果;其实就是需要传入Optional类型参数,并返回Optional类型
System.out.println("********************flatMap()转换值 需要传入Optional类型*********************");
student.setPosition("Position");
String position = Optional.ofNullable(student)
.flatMap(u -> u.getPosition()).orElse("defaultPosition");
System.out.println("back10:"+position);
//filter() 接受一个 Predicate 参数,返回测试结果为 true 的值。
// 如果测试结果为 false,会返回一个空的 Optional。
System.out.println("*******************filter() 接受判断表达式,返回判断结果**********************");
Optional<Student> optional11 = Optional.ofNullable(student).filter(u->u.getName()!=null&&u.getName().contains("1"));
System.out.println("back11:"+optional11.isPresent());
//使用Optional避免空指针来取值
System.out.println("*******************使用Optional避免空指针来取值**********************");
String code = Optional.ofNullable(new User())
.flatMap(User::getAddress)
.flatMap(Address::getCountry)
.map(Country::getCode)
.orElse("defaultcode");
System.out.println("back12:"+code);
System.out.println("*****************************************");
}
public static Student createStudent(){
System.out.println("CreateStudent loading......");
return new Student("Createjohn",0);
}
public static void ifFuction(Student student){
System.out.println("ifFuction loading......");
}
static class Student{
public String name;
public int age;
public String position;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", position=" + position +
'}';
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void setPosition(String position) {
this.position = position;
}
public Optional<String> getPosition() {
return Optional.ofNullable(position);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
static class User{
Address address;
public Optional<Address> getAddress() {
return Optional.ofNullable(address);
}
}
static class Address{
Country country;
public Optional<Country> getCountry() {
return Optional.ofNullable(country);
}
}
static class Country{
String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
}
打印
"C:\Program Files\Java\jdk1.8.0_92\bin\java.exe" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:60721,suspend=y,server=n -javaagent:C:\Users\du'me\.IntelliJIdea2019.2\system\captureAgent\debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_92\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\rt.jar;D:\ideaworkspaces\boot\target\classes;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.0.4.RELEASE\spring-boot-starter-jdbc-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot-starter\2.0.4.RELEASE\spring-boot-starter-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot\2.0.4.RELEASE\spring-boot-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.0.4.RELEASE\spring-boot-autoconfigure-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.0.4.RELEASE\spring-boot-starter-logging-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\du'me\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\du'me\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.10.0\log4j-to-slf4j-2.10.0.jar;C:\Users\du'me\.m2\repository\org\apache\logging\log4j\log4j-api\2.10.0\log4j-api-2.10.0.jar;C:\Users\du'me\.m2\repository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;C:\Users\du'me\.m2\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;C:\Users\du'me\.m2\repository\org\yaml\snakeyaml\1.19\snakeyaml-1.19.jar;C:\Users\du'me\.m2\repository\com\zaxxer\HikariCP\2.7.9\HikariCP-2.7.9.jar;C:\Users\du'me\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-jdbc\5.0.8.RELEASE\spring-jdbc-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-beans\5.0.8.RELEASE\spring-beans-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-tx\5.0.8.RELEASE\spring-tx-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot-starter-thymeleaf\2.0.4.RELEASE\spring-boot-starter-thymeleaf-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\org\thymeleaf\thymeleaf-spring5\3.0.9.RELEASE\thymeleaf-spring5-3.0.9.RELEASE.jar;C:\Users\du'me\.m2\repository\org\thymeleaf\thymeleaf\3.0.9.RELEASE\thymeleaf-3.0.9.RELEASE.jar;C:\Users\du'me\.m2\repository\org\attoparser\attoparser\2.0.4.RELEASE\attoparser-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\org\unbescape\unbescape\1.1.5.RELEASE\unbescape-1.1.5.RELEASE.jar;C:\Users\du'me\.m2\repository\org\thymeleaf\extras\thymeleaf-extras-java8time\3.0.1.RELEASE\thymeleaf-extras-java8time-3.0.1.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.0.4.RELEASE\spring-boot-starter-web-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot-starter-json\2.0.4.RELEASE\spring-boot-starter-json-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.9.6\jackson-databind-2.9.6.jar;C:\Users\du'me\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;C:\Users\du'me\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.9.6\jackson-core-2.9.6.jar;C:\Users\du'me\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.6\jackson-datatype-jdk8-2.9.6.jar;C:\Users\du'me\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.6\jackson-datatype-jsr310-2.9.6.jar;C:\Users\du'me\.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.6\jackson-module-parameter-names-2.9.6.jar;C:\Users\du'me\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\2.0.4.RELEASE\spring-boot-starter-tomcat-2.0.4.RELEASE.jar;C:\Users\du'me\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.32\tomcat-embed-core-8.5.32.jar;C:\Users\du'me\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.32\tomcat-embed-el-8.5.32.jar;C:\Users\du'me\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.32\tomcat-embed-websocket-8.5.32.jar;C:\Users\du'me\.m2\repository\org\hibernate\validator\hibernate-validator\6.0.11.Final\hibernate-validator-6.0.11.Final.jar;C:\Users\du'me\.m2\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;C:\Users\du'me\.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\du'me\.m2\repository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;C:\Users\du'me\.m2\repository\org\openjfx\javafx.base\11.0.0-SNAPSHOT\javafx.base-11.0.0-20180702.224858-3.jar;C:\Users\du'me\.m2\repository\org\openjfx\javafx.base\11.0.0-SNAPSHOT\javafx.base-11.0.0-20180702.223831-2-linux.jar;C:\Users\du'me\.m2\repository\org\openjfx\javafx.base\11.0.0-SNAPSHOT\javafx.base-11.0.0-20180702.224858-3-mac.jar;C:\Users\du'me\.m2\repository\org\openjfx\javafx.base\11.0.0-SNAPSHOT\javafx.base-11.0.0-20180629.175051-1-win.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-web\5.0.8.RELEASE\spring-web-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-webmvc\5.0.8.RELEASE\spring-webmvc-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-aop\5.0.8.RELEASE\spring-aop-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-context\5.0.8.RELEASE\spring-context-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-expression\5.0.8.RELEASE\spring-expression-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-core\5.0.8.RELEASE\spring-core-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\springframework\spring-jcl\5.0.8.RELEASE\spring-jcl-5.0.8.RELEASE.jar;C:\Users\du'me\.m2\repository\org\apache\commons\commons-lang3\3.7\commons-lang3-3.7.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-spring\1.4.0\shiro-spring-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-core\1.4.0\shiro-core-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-lang\1.4.0\shiro-lang-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-crypto-hash\1.4.0\shiro-crypto-hash-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-crypto-core\1.4.0\shiro-crypto-core-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-crypto-cipher\1.4.0\shiro-crypto-cipher-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-config-core\1.4.0\shiro-config-core-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-config-ogdl\1.4.0\shiro-config-ogdl-1.4.0.jar;C:\Users\du'me\.m2\repository\commons-beanutils\commons-beanutils\1.9.3\commons-beanutils-1.9.3.jar;C:\Users\du'me\.m2\repository\commons-collections\commons-collections\3.2.2\commons-collections-3.2.2.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-event\1.4.0\shiro-event-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-web\1.4.0\shiro-web-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-ehcache\1.4.0\shiro-ehcache-1.4.0.jar;C:\Users\du'me\.m2\repository\org\apache\shiro\shiro-cache\1.4.0\shiro-cache-1.4.0.jar;C:\Users\du'me\.m2\repository\net\sf\ehcache\ehcache-core\2.6.11\ehcache-core-2.6.11.jar;C:\Users\du'me\.m2\repository\junit\junit\4.13.2\junit-4.13.2.jar;C:\Users\du'me\.m2\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar;C:\Users\du'me\.m2\repository\org\junit\jupiter\junit-jupiter\5.8.0\junit-jupiter-5.8.0.jar;C:\Users\du'me\.m2\repository\org\junit\jupiter\junit-jupiter-api\5.1.1\junit-jupiter-api-5.1.1.jar;C:\Users\du'me\.m2\repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;C:\Users\du'me\.m2\repository\org\opentest4j\opentest4j\1.0.0\opentest4j-1.0.0.jar;C:\Users\du'me\.m2\repository\org\junit\platform\junit-platform-commons\1.1.1\junit-platform-commons-1.1.1.jar;C:\Users\du'me\.m2\repository\org\junit\jupiter\junit-jupiter-params\5.1.1\junit-jupiter-params-5.1.1.jar;C:\Users\du'me\.m2\repository\org\junit\jupiter\junit-jupiter-engine\5.1.1\junit-jupiter-engine-5.1.1.jar;C:\Users\du'me\.m2\repository\org\junit\platform\junit-platform-engine\1.1.1\junit-platform-engine-1.1.1.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2019.2.4\lib\idea_rt.jar" com.dume.boot.code.OptionalDemo
Connected to the target VM, address: '127.0.0.1:60721', transport: 'socket'
*******************isPresent判断值不为空,get返回对象**********************
back1:Student{name='john1', age=11, position=null}
*********************ifPresent判断不为空, 并执行Lambda 表达式********************
ifFuction loading......
*********************orElse判断不为空,否则返回默认值********************
back2:Student{name='john2', age=22, position=null}
*******************orElseGet不为空时返回值;为空时作为参数传入函数式接口,并返回执行后的参数**********************
CreateStudent loading......
CreateStudent loading......
back3:Student{name='Createjohn', age=0, position=null}
back4:Student{name='Createjohn', age=0, position=null}
*********************当都不为空时,orElse依然会执行,orElseGet不会执行********************
CreateStudent loading......
back5:Student{name='john1', age=11, position=null}
back6:Student{name='john1', age=11, position=null}
*********************orElseThrow当为空时,抛出自定义异常********************
java.lang.IllegalArgumentException
at com.dume.boot.code.OptionalDemo.lambda$main$3(OptionalDemo.java:58)
at java.util.Optional.orElseThrow(Optional.java:290)
at com.dume.boot.code.OptionalDemo.main(OptionalDemo.java:58)
*********************map转换值********************
back8:DEFUAFT
back9:DEFUAFT
********************flatMap()转换值 需要传入Optional类型*********************
back10:Position
*******************filter() 接受判断表达式,返回判断结果**********************
back11:true
*******************使用Optional避免空指针来取值**********************
back12:defaultcode
*****************************************
Disconnected from the target VM, address: '127.0.0.1:60721', transport: 'socket'
Process finished with exit code 0