Java8 Optional为空处理
package com.example.cesium.utils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.util.Optional; public class OptionalTest { public static void main(String[] args) { //1使用前 Student student = new Student("charkey", 20, 50, new Address()); //student = null; if (student != null) { String name = student.getName(); System.out.println("name = " + name); } //1使用后 Optional.ofNullable(student).map(Student::getName).ifPresent(System.out::println); //2使用前 if (student == null) { new Student(); } else { student = student; } //2使用后 Student student1 = Optional.ofNullable(student).orElseGet(() -> new Student()); System.out.println("student1 = " + student1); //3使用前 if (student == null) { throw new RuntimeException("1.用户名为空"); } //3使用后 //student = null; Optional.ofNullable(student).orElseThrow(() -> new RuntimeException("2.用户名为空")); //4使用前 if (student != null) { int sore = student.getScore(); if (sore < 60) { System.out.println("1.不及格处理。。。"); } } //4使用后 Optional.ofNullable(student).map(Student::getScore).filter(score -> score < 60).ifPresent(stu -> { System.out.println("2.不及格处理。。。"); }); Optional.ofNullable(student).filter(stu -> stu.getScore() < 60).orElseGet(() -> { System.out.println("2.及格处理。。。"); return new Student(); }); //5使用前 Address address1 = new Address("北京", "001", new Country("中国", "000")); student = new Student("charkey", 20, 50, address1); if (student != null) { Address address = student.getAddress(); if (address != null) { Country city = address.getCountry(); if (city != null) { if (city.getCode() != null) { String code = city.getCode().toLowerCase(); System.out.println(code); } } } } //5使用后 Optional.ofNullable(student).flatMap(s -> Optional.ofNullable(s.getAddress())).flatMap(s -> Optional.ofNullable(s.getCountry())).map(Country::getCode).ifPresent(System.out::println); } @Data @AllArgsConstructor @NoArgsConstructor @ToString public static class Student { private String name; private Integer age; private Integer score; private Address address; } @Data @AllArgsConstructor @NoArgsConstructor public static class Address { private String name; private String code; private Country country; } @Data @AllArgsConstructor @NoArgsConstructor public static class Country { private String name; private String code; } }