File tree Expand file tree Collapse file tree
src/main/java/com/putsoft/guava/base Expand file tree Collapse file tree Original file line number Diff line number Diff line change 2121 <version >3.8.1</version >
2222 <scope >test</scope >
2323 </dependency >
24+
25+ <dependency >
26+ <groupId >com.google.guava</groupId >
27+ <artifactId >guava</artifactId >
28+ <version >18.0</version >
29+ <scope >complie</scope >
30+ </dependency >
31+
32+
2433 </dependencies >
2534</project >
Original file line number Diff line number Diff line change 1+ package com .putsoft .guava .base ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
6+ import com .google .common .base .Function ;
7+ import com .google .common .base .Optional ;
8+
9+ public class OptionalDemo {
10+
11+
12+
13+ public static void main (String [] args ) {
14+
15+
16+ Optional <Integer > possible =Optional .of (1 );
17+
18+ //不为null 返回true
19+ possible .isPresent ();
20+
21+ //保证获取的不为null,为null则抛出异常
22+ possible .get ();
23+
24+ //为了遍历使用,for(T obj:asSet)
25+ possible .asSet ();
26+
27+ //如果为null,则返回传入的值
28+ possible .or (5 );
29+
30+ //如果为null,则返回null
31+ possible .orNull ();
32+
33+ //创建为Absent 空对象,没有实际意义
34+ Optional .absent ();
35+
36+ //如果实例为null,曾返回absent,如果不为null,则应由function转换
37+ possible .transform (new ObjectConver ());
38+
39+ //如果为空 返回Absent
40+ Optional .fromNullable (444 );
41+ Optional .fromNullable (null );
42+
43+ List <Optional <String >> list =new ArrayList <Optional <String >>();
44+ //过滤一个容器里的null元素
45+ Optional .presentInstances (list );
46+
47+ }
48+
49+ }
50+
51+ //类型转换
52+ class ObjectConver implements Function <Integer , Double >{
53+
54+ @ Override
55+ public Double apply (Integer input ) {
56+ return Double .valueOf (input );
57+ }
58+
59+ }
You can’t perform that action at this time.
0 commit comments