Guava
中嘉網路 (bb 寬頻)!
李書豪
Agenda
• Introduction
• Strings
• Ordering / ComparisonChain
• Collections
• Predicate / Function
• Q&A
3
What Guava Is
4
Java version
• Before Java 1.5

• Java 1.5

• Java 1.6 / 1.7

• Java 1.8
Java version
• Before Java 1.5

• Java 1.5

• Java 1.6 / 1.7

• Java 1.8
Unsupport
Guava (JDK5 Backport)
Guava release 17
Consider
App 使⽤用 Guava 開發
http://www.appbrain.com/stats/libraries/details/guava/google-guava
Strings
8
測驗時間
Arrays.toString(“,apple,,banana,”.split(“,”))
的輸出是以下何者?
2 ) , apple , , banana ,
3 ) , apple , , banana
1 ) null, apple , null, banana , null
4 ) apple , banana
測驗時間
Arrays.toString(“,apple,,banana,”.split(“,”))
的輸出是以下何者?
2 ) , apple , , banana ,
3 ) , apple , , banana
1 ) null, apple , null, banana , null
4 ) apple , banana
但,其實你想
要的是這個
在Java8之前,好像少了什麼?
之前,每次使用 String.split 後,你總是會問
A CB
A CB
“A,B,C”
“A,B,C”
Split
?
終於在Java8⾒見到 join !
String.join(",", ",apple,,banana,".split(","));
,apple,,banana
“,apple,,banana”",apple,,banana,"== is FALSE
13
Splitter / Joiner
Splitter.on(“,”).split(“,apple,,banana,");
Joiner.on(“,”).join( ___ );
“,apple,,banana,”",apple,,banana,"== is TRUE
“,apple,,banana,”
空(empty)資料不是我想要的
14
Splitter.omitEmptyStrings()
分割字串時,忽略空(empty)的資料
空(null)資料也不是我想要的
15
Joiner.skipNulls()
合併集合時,忽略空(null)的資料
空(null)資料我⼜又需要它了
16
Joiner.useForNull( nullText )
合併集合時,為空(null)值補上預設字元
Splitter 實⽤用功能
17
.trimResults()
為每個分割的結果,去除前後空⽩白字元
.fixedLength( length )
以固定的⻑⾧長度,分割字串
Split後成為……Map!?
18
.withKeyValueSeparator( separator )
為每個分割的結果,再增加鍵值分割,
完成分割時,會回傳⼀一組 Map
ComparisonChain
19
Ordering and
⼀一個平凡的class
還能變什麼花樣?
____是對的
ORDER BY name, quarter, value
NAS:AAPL 13Q1 250
NAS:AAPL 13Q2 350
NAS:GOOG 13Q1 100
NAS:GOOD 13Q2 200
NAS:MFST 13Q1 300
ORDER BY name,
quarter, value
NAS:AAPL 600
NAS:AAPL 13Q1 250
NAS:AAPL 13Q2 350
NAS:GOOG 300
NAS:GOOD 13Q1 100
NAS:GOOD 13Q2 200
13Q1 350
13Q2 550
name null @ last
quarter null @ first
____永遠是對的
23
ComparisonChain Awesome!
太簡單了
24
Ordering
[ Barack Obama	
, Bill Gates	
, Steve Jobs	
, Abola Lee ]	
[ Abola Lee 	
, Barack Obama	
, Bill Gates	
, Steve Jobs ]	
Collections.sort(names)
Collections.sort(names,
byReverseLengthThenName)
http://qconsf.com/sf2012/dl/qcon-sanfran-2012/slides/
KevinBourrillion_AnOverviewOfGuavaGoogleCoreLibrariesForJava.pdf
25
Ordering
Start with:
http://qconsf.com/sf2012/dl/qcon-sanfran-2012/slides/
KevinBourrillion_AnOverviewOfGuavaGoogleCoreLibrariesForJava.pdf
• Ordering.natural()
• new Ordering() { public int compare(...) {...} }
• Ordering.explicit("壹", "貳", "叄", "肆");
IncomparableValueException注意!
26
Ordering
Then chaining method:
● reverse()
● compound(Comparator)
● onResultOf(Function)
● nullsFirst()
● nullsLast()
http://qconsf.com/sf2012/dl/qcon-sanfran-2012/slides/
KevinBourrillion_AnOverviewOfGuavaGoogleCoreLibrariesForJava.pdf
27
toString()
start()
stop()
reset()
createStarted()
createUnstarted()
Stopwatch
Collections
28
我們可能經常在寫這樣的程式
Java 7 way
List Set Map
Lists.newArrayList() Sets.newHashSet() Maps.newHashMap()
Lists.newLinkedList() Sets.newLinkedHashSet() Maps.newLinkedHashMap()
Sets.newTreeSet() Maps.newTreeMap()
Sets.newConcurrentHashSet() Maps.newConcurrentMap()
Maps.newEnumMap()
Guava way Static constructors
Item 1: Consider static
factory methods instead of
constructors
Collection Utilities
資料來源:https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained
笛卡爾乘積
33
A1
A2
A3
B1
B2
C1x x =
A1 B1 C1
A1 B2 C1
A2 B1 C1
A2 B2 C1
A3 B1 C1
A3 B2 C1
34
Collection Utilities
利⽤用List.partition 建⽴立簡易的資料分⾴頁
SELECT * FROM …
LIMIT 5 OFFSET 10
Guava 擴展集合類
35
Some countable prob
java.lang.NullPointerException 如影隨形,揮之不去
Guava way!
南 3
⻄西 3
北 3
三萬 2
東 1
南 3
⻄西 3
北 3
三萬 2
東
count(“北”)
setCount(K, Count)
elementSet()
!
add(K)
add(K, Count)
!
remove(K)
remove(K, Count)
Multiset - 加了計數器的Set
add(“東”)
add(“⻄西”)
add(“北”)
add(“南”)
add(“南”)
add(“三萬”) add(“北”)
add(“北”)
add(“⻄西”) add(“三萬”)
add(“東”)
add(“東”)
add(“⻄西”)
add(“南”)
MultiSet
3
Map<K, Integer>資料結構:
Implementations: HashMultiset, TreeMultiset,
Set<K>
LinkedHashMultiset
東 1
南 3
⻄西 3
北 3
三
萬
2
滿意 [A,E,I,O,U]
尚可 [X,Y,Z]
差勁 [M,N,P,Q]
滿意 [A,E,I,O,U]
尚可 [B,X,Y,Z]
差勁 [M,N,P,Q]
尚可 BVoting
Guava way!
Multimap - 字元陣列
MultiMap
with JAVA style
Map<K, List<V>> / Map<K, Set<V>>資料結構:
List Implementations: ArrayListMultimap, LinkedListMultimap
HashMultimap, LinkedHashMultimap,
TreeMultimap
Set Implementations:
put(“尚可”, “X”)
put(“尚可”, “Z”)
put(“滿意”, “A”)
put(“差勁”, “P”)
put(“尚可”, “Y”)
put(“滿意”, “U”)
滿意 [A,E,I,O,U]
尚可 [B,X,Y,Z]
差勁 [M,N,P,Q]
40
Multimap - 字元陣列
get(K) 回傳 Collection<V>
pub(K,V) 將V加⼊入K的Collection
pubAll(K,Collection) 將集合中的值全部加⼊入
remove(K,V) 移除K collection中的V值
removeAll(K) 移除K
asMap() 回傳Map<K,Collection<V>>
values() 回傳Collection<V>
Map<K, List<V>> / Map<K, Set<V>>資料結構:
with JAVA style
41
Map<K, List<V>>
List<List<V>>
values()
[[A,E,I,O,U]!
, [B,X,Y,Z]!
, [M,N,P,Q]]
Multimap<K, V>
List<V>
values()
[A,E,I,O,U,B!
,X,Y,Z,M,N,P,Q]
[A, B, C, D x 2, E x 2, F x 2, G x 2,
H x 3, I x 3, J x 3, K x 2, L x 2, M x
2, N x 2, O, P]!
滿意 [A,B,C,D,E,F,G,H,I,J]
尚可 [D,E,F,G,H,I,J,K,L,M,N]
差勁 [H,I,J,K,L,M,N,O,P]
BiMap - Value Key
BiMap
台積電
鴻海
宏達電
2317
2330
2498
keys values
Implementations:HashBiMap
stock quartly value
goog 13Q1 283
goog 13Q1 3278
goog 13Q1 982
msft 13Q2 883
aapl 13Q1 3341
aapl 13Q2 367
….. ….. …..
NAS:GOOG NAS:MSFT NAS:AAPL
13Q1 16858 24519 57594
13Q2 14893 18529 37472
13Q3 14105 19896 35323
13Q4 12951 20489 43603
Pivot
sum
Pivoting plz wait……
Get cell value………
stock quartly value
goog 13Q1 283
goog 13Q1 3278
goog 13Q1 982
msft 13Q2 883
aapl 13Q1 3341
aapl 13Q2 367
….. ….. …..
NAS:GOOG NAS:MSFT NAS:AAPL
13Q1 16858 24519 57594
13Q2 14893 18529 37472
13Q3 14105 19896 35323
13Q4 12951 20489 43603
Pivot
sum
Guava way: Table
Get value from Table
Map<R, Map<C, V>>
Table<R,C,V> - ⼆二維陣列
NAS:GOOG NAS:MSFT NAS:AAPL
13Q1 16858 24519 57594
13Q2 14893 18529 37472
13Q3 14105 19896 35323
13Q4 12951 20489 43603
資料結構:
Implementations: HashBasedTable,
TreeBasedTable
R Ccontains(R, C)
!
get(R, C)
!
put(R,C, V)
!
remove(R, C)
Boolean
!
V
46
NAS:GOOG NAS:MSFT NAS:AAPL
13Q1 16858 24519 57594
13Q2 14893 18529 37472
13Q3 14105 19896 35323
13Q4 12951 20489 43603
R C
Table<R,C,V> - 抽取⾏行列資料
column(C)
Map<K, V>
row(R) Map<C, V>
{ 13Q4=12951	
, 13Q3=14105	
, 13Q2=14893	
, 13Q1=16858}	
{ NAS:AAPL=37472	
, NAS:MSFT=18529	
, NAS:GOOG=14893}
47
NAS:GOOG NAS:MSFT NAS:AAPL
13Q1 16858 24519 57594
13Q2 14893 18529 37472
13Q3 14105 19896 35323
13Q4 12951 20489 43603
R C
Table<R,C,V> - 抽取⾏行列資料
columnKeySet()
containsColumn(C)
containsRow(R) rowKeySet()
boolean Set<R>
[13Q4, 13Q3, 13Q2, 13Q1]
Set<C>
[NAS:AAPL, NAS:MSFT, NAS:GOOG]
boolean
範圍判定只能這樣寫嗎?
Guava way! RangeMap
https://code.google.com/p/guava-libraries/wiki/RangesExplained
RangeMap
RangeMap
Map<Range<K>, V>資料結構:
Implementations: TreeRangeMap
@Beta
51
RangeMap - 操作特性
[1 .. 10]
[1 .. 3] (3 .. 6) [6 .. 10]
[1 .. 3] (3 .. 6) [6 .. 10]
(10 .. 20)
[1 .. 3] (3 .. 5)
(11 .. 20)
rangeMap.put(Range.closed(1, 10), "foo");
rangeMap.put(Range.open(3, 6), "foo");
rangeMap.put(Range.open(10,20), "foo");
rangeMap.remove(Range.closed(5, 11));
52
Range
(a .. b) open! a < x < b
[a .. b] closed a <= x <= b
[a .. b)! closedOpen a <= x < b
(a .. b] openClosed a < x <= b
(a .. ∞) greaterThan a < x
[a .. ∞) atLeast a <= x
(-∞.. b) leaseThan x < b
(-∞.. b] atMost x <= b
(-∞.. ∞) all all values
Range - example
a
b
8/1 8/2
12:00 12:00
intersection
lowerEndpoint lowerEndpoint
Why immutable ?
• defensive programming
JDK 有 unmodifyableXXX
•不實⽤用且冗⻑⾧長(unwieldy and verbose)
•還是可變……(unsafe)
•效率較差(inefficient)
!
(from: https://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained)
Guava Immutable example
ImmutableXXX 提供
了 .of( … ) ⽅方便建⽴立
UnsupportedOperation
Exception
IDE warring!
& Function
57
Predicate
filter
transform
Example from: https://code.google.com/p/guava-libraries/wiki/FunctionalExplained
更加流暢的寫法
字串轉字數
必需要符合
篩選與轉換
真相是....
61
考⽣生 科⺫⽬目 題數
考⽣生A 國⽂文 48
考⽣生A 英⽂文 39
考⽣生A 數學 26
考⽣生B 國⽂文 43
考⽣生B 英⽂文 30
考⽣生B 數學 20
考⽣生C 國⽂文 44
考⽣生C 英⽂文 40
考⽣生C 數學 27
考⽣生D 國⽂文 18
考⽣生D 英⽂文 25
[45 .. 48] A++
[43 .. 44] A+
[41 .. 42] A
[35 .. 40] B++
[30 .. 34] B+
[19 .. 29] B
[ 0 .. 18] C
考⽣生 科⺫⽬目 題數
考⽣生A 國⽂文 48
考⽣生B 國⽂文 43
考⽣生C 國⽂文 44
考⽣生D 國⽂文 18
考⽣生 科⺫⽬目 等級
考⽣生A 國⽂文 A++
考⽣生B 國⽂文 A+
考⽣生C 國⽂文 A+
考⽣生D 國⽂文 C
filter
國⽂文
transform
Need Result
Predicate<F>
62
○  determines true or false for a given F 	

○ boolean apply(F input)
determines
and use
63
還記得 Range 嗎?
public final class Range<C extends Comparable>
implements Predicate<C>, Serializable {…}
[51, 52, 53, 54, 55, 56, 57, 58, 59, 60]
Function<F, T>
64
○  one way transformation of F into T 	

○ T apply(F input)
determines
and use
Integration
65
66
其實
Item 47: Know and use the
libraries
Thank you
68

Guava 讓你的程式碼簡潔有力 2014 Java Developer Day