Optional 是一个封装对象, 主要用处是防止空指针异常, 避免因不断判断是否为空造成臃肿的代码。
1. Optional 的各种API使用方法
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Optional 对象
* 可以优雅地避免空指针异常
*/
public class Demo8 {
public static void main(String[] args) {
Author author = getAuthor();
// 创建Optional对象 Optional.ofNullable(author) 无论author是否为空, 都能创建对象
Optional<Author> optional = Optional.ofNullable(author);
optional.ifPresent(newAuthor -> System.out.println(newAuthor.getName()));
System.out.println("================== 1 ======================");
// 直接从方法中返回Optional对象
Optional<Author> authorOptional = getAuthorOptional();
authorOptional.ifPresent(newAuthor -> System.out.println(newAuthor.getName()));
System.out.println("================== 2 ======================");
// 从Optional中获取值
Author author1 = authorOptional.get(); // 不推荐使用, 如果Optional为空, 会出现NoSuchElementException问题
Author author2 = authorOptional.orElseGet(() -> new Author()); // 如果Optional为空, 返回新创建的默认数据new Author()
System.out.println(author2.getName());
// 如果Optional为空, 返回自定义异常
try {
Author author3 = authorOptional.orElseThrow(() -> new RuntimeException("数据为空"));
System.out.println(author3);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("================== 3 ======================");
// 通过Optional使用过滤方法 filter()
authorOptional.filter(author3 -> author3.getAge() > 18).ifPresent(author3 -> System.out.println(author3.getName()));
System.out.println("================== 4 ======================");
// 通过Optional使用判断方法 isPresent()
if (authorOptional.isPresent()){
System.out.println(authorOptional.get().getName());
}
System.out.println("================== 5 ======================");
// 通过Optional使用数据转换方法, 获取对应的书籍 map()
authorOptional.map(author3 -> author3.getBooks()).ifPresent(books -> System.out.println(books));
}
/**
* 作者数据准备
* @return
*/
private static Author getAuthor(){
// 数据初始化
Author author = new Author(1,"天蚕土豆",29,"白金作家,玄幻小说巅峰作家",null);
return author;
}
/**
* 作者数据准备, 封装成Optional对象
* @return
*/
private static Optional<Author> getAuthorOptional(){
// 数据初始化
Author author = new Author(1,"天蚕土豆",29,"白金作家,玄幻小说巅峰作家",null);
List<Book> books1 = new ArrayList<>();
books1.add(new Book(1,"斗破苍穹","玄幻",100,"三十年河东,三十年河西,莫欺少年穷! 年仅15岁的萧家废物,于此地,立下了誓言,从今以后便一步步走向斗气大陆巅峰"));
books1.add(new Book(2,"武动乾坤","玄幻",98,"大炎王朝天都郡炎城青阳镇,落魄的林氏子弟林动在山洞间偶然捡到一块神秘的石符而走上的逆袭之路"));
author.setBooks(books1);
return Optional.ofNullable(author);
}
}
2. Author 和 Book 实体
import java.util.List;
/**
* 作家
*/
public class Author {
private Integer id;
private String name;
private Integer age;
private String intro; // 简介
private List<Book> books; // 作品
public Author(Integer id, String name, Integer age, String intro, List<Book> books) {
this.id = id;
this.name = name;
this.age = age;
this.intro = intro;
this.books = books;
}
public Author() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "Author{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", intro='" + intro + '\'' +
", books=" + books +
'}';
}
}
/**
* 作品
*/
public class Book {
private Integer id;
private String name;
private String category; // 分类
private Integer score; // 评分
private String intro; // 简介
public Book(Integer id, String name, String category, Integer score, String intro) {
this.id = id;
this.name = name;
this.category = category;
this.score = score;
this.intro = intro;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", category='" + category + '\'' +
", score=" + score +
", intro='" + intro + '\'' +
'}';
}
}