欢迎来到阿八个人博客网站。本
阿八个人博客
网站提供最新的站长新闻,各种互联网资讯。
喜欢本站的朋友可以收藏本站,或者加QQ:我们大家一起来交流技术!
URL链接:https://www.abboke.com/jsh/2019/0612/2617.html
Optiona 是 JDK1.8 中的一个很流弊的新特性,每个接触JAVA的都遇到过 NPE(NullPointerException),1.8中Optiona帮助我们很好的避免了这一现象,借助源码一步步讲解 Optional
和使用场景
of/empty/ofNullable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| @Test public void test1() {
Student student = null;
Optional<Student> op1 = Optional.of(student);
Optional<Student> op2 = Optional.empty();
Optional<Student> op3 = Optional.ofNullable(student); }
|
get/isPresent
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @Test public void test2() {
Optional<Student> op = Optional.ofNullable(null);
System.out.println(op.isPresent());
System.out.println(op.get()); }
|
orElse/orElseGet/orElseThrow
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| @Test public void test3() {
Student student = null;
Student s1 = Optional.ofNullable(student).orElseGet(Student::new); System.out.println(s1);
Student s2 = (Student) Optional.ofNullable(student).orElse(new Student(1L, "枫", "1837307557@qq.com", 22)); System.out.println(s2);
Student s3 = Optional.ofNullable(student).orElseThrow(() -> new RuntimeException("哈哈,报错了吧")); System.out.println(s3);
}
|
其他实例
- fiter/map
1 2 3 4 5 6 7 8 9 10 11
| @Test public void test4() {
String filter = Optional.ofNullable("aadasdsa").filter((value) -> value.length() > 5).get(); System.out.println(filter);
String map = Optional.ofNullable("aadasdsa").map(String::toUpperCase).get(); System.out.println(map); }
|
- Optional转集合
将一个Optional转为List或者Set
Optional是一个集合,虽然里面只有0或者1个元素,但它一样是一个集合。如果要转为List或者Set,一般的写法可以是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public static <T> List<T> toList(Optional<T> option) { return option. map(Collections::singletonList). orElse(Collections.emptyList()); }
或者更传统的写法:
public static <T> List<T> toList(Optional<T> option) { if (option.isPresent()) return Collections.singletonList(option.get()); else return Collections.emptyList(); }
但是在java8里,其实只需要这么写:
import static java.util.stream.Collectors.*;
List<String> list = collect(opt, toList());
Set<String> set = collect(opt, toSet());
|
在说点什么
程序猿要与时俱进,JDK9都快出了你难道还要守着6和7吗,当你认为JDK8有BUG的时候你可曾知道当初JDK6-7也是这样过来的…
对本章有建议的可以在下方留言,会第一时间修改