File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed
src/main/java/com/xu/java8/Optional Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ ##optional类
2
+ - 创建一个空Optional对象
3
+ 输出的是一个空的optional对象
4
+ ```
5
+ Optional<String> optional = Optional.empty();
6
+ System.out.println(optional);
7
+ ##:Optional.empty
8
+ ```
9
+ - 创建一个非空Optional对象
10
+ 如果person是null,将会立即抛出,而不是访问person的属性时获得一个潜在的错误
11
+
12
+ ```
13
+ Person person = new Person("xu","hua");
14
+ Optional<Person> optional2 = Optional.of(person);
15
+ System.out.println(optional2);
16
+ System.out.println(optional2.get());
17
+ System.out.println(optional2.get().firstName);
18
+ ##:Optional[xuhua]
19
+ xuhua
20
+ xu
21
+ ```
22
+ - 判断对象是否存在
23
+ ```
24
+ System.out.println(optional.isPresent());
25
+ System.out.println(optional2.isPresent());
26
+ ##:false
27
+ true
28
+ ```
29
+ - 如果Optional为空返回默认值
30
+ ```
31
+ System.out.println(optional.orElse("fallback"));
32
+ optional.ifPresent(System.out::println);
33
+ ##:fallback
34
+ xuhua
35
+ ```
Original file line number Diff line number Diff line change @@ -16,11 +16,14 @@ public static void main(String[] args) {
16
16
17
17
/**创建一个空Optional对象*/
18
18
Optional <String > optional = Optional .empty ();
19
+ System .out .println (optional );
19
20
20
21
/**创建Optional对象有一个非空值*/
21
22
Person person = new Person ("xu" ,"hua" );
22
23
Optional <Person > optional2 = Optional .of (person );//如果person是null,将会立即抛出,而不是访问person的属性时获得一个潜在的错误
23
24
System .out .println (optional2 );
25
+ System .out .println (optional2 .get ());
26
+ System .out .println (optional2 .get ().firstName );
24
27
25
28
/**判断对象是否存在*/
26
29
System .out .println (optional .isPresent ());
You can’t perform that action at this time.
0 commit comments