安全获取值
大约 1 分钟函数式编程Optional
不推荐使用get方法
public static void main(String[] args) {
Optional<Author> author = getAuthor();
Author author1 = author.get();
}
private static Optional<Author> getAuthor() {
//数据初始化
Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
return Optional.ofNullable(null);
}
程序会发生异常:
Exception in thread "main" java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at com.sanfen.StreamDemo01.main(StreamDemo01.java:23)
Process finished with exit code 1
orElseGet(默认值)方法:Optional封装的数据为null时,返回默认值。
public static void main(String[] args) {
Optional<Author> author = getAuthor();
Author author1 = author.orElseGet(() -> new Author());
System.out.println(author1);
}
private static Optional<Author> getAuthor() {
//数据初始化
Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
return Optional.ofNullable(null);
}
Author(id=null, name=null, age=0, intro=null, books=null)
Process finished with exit code 0
orElseThrow方法:Optional封装的数据为null时,抛出异常。
public static void main(String[] args) throws Throwable {
Optional<Author> author = getAuthor();
author.orElseThrow(() -> new Exception("author异常"));
}
private static Optional<Author> getAuthor() {
//数据初始化
Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
return Optional.ofNullable(null);
}
结果:
Exception in thread "main" java.lang.Exception: author异常
at com.sanfen.StreamDemo01.lambda$main$0(StreamDemo01.java:20)
at java.util.Optional.orElseThrow(Optional.java:290)
at com.sanfen.StreamDemo01.main(StreamDemo01.java:20)
Process finished with exit code 1