-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1257 lines (976 loc) · 40.5 KB
/
index.html
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mmmm... Google Guava</title>
<meta name="description"
content="A quick intro into Google's Guava library, best described as the ultimate Java-Painkiller ;-)">
<meta name="author" content="Konrad Malawski">
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>
<link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic' rel='stylesheet'
type='text/css'>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/print.css" type="text/css" media="print">
<link rel="stylesheet" href="lib/zenburn.css">
</head>
<body>
<div class="reveal">
<div class="state-background"></div>
<div class="slides">
<section>
<h1>
Mmmm... <br/> Google Guava
<img src="assets/images/guava.png" alt="guava"/>
</h1>
<script>
// Delicously hacky. Look away.
if (navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/i)) document.write('<p style="color: rgba(0,0,0,0.3); text-shadow: none;">(' + 'Tap to navigate' + ')</p>');
</script>
</section>
<section>
<h2>About me</h2>
<p>
<img src="./assets/images/about_me.png" alt="about me" style="background: white;"/>
</p>
</section>
<section>
<section>
<h2>Guava is...</h2>
<ul>
<li class="fragment">a <b>fruit</b></li>
</ul>
</section>
<section>
<h2>Guava is...</h2>
<ul>
<li class="fragment">a set of <strong>utility</strong> classes and methods</li>
<li class="fragment">some quite neat <strong>collection</strong> implementations (AKA. google-collections)
</li>
<li class="fragment">comparable to <em>Apache Commons</em></li>
<li class="fragment">basically... a <em><strong>painkiller</strong></em> and <em><strong>natural extension</strong></em> for Java (stdlib)</li>
</ul>
</section>
</section>
<section>
<h2>
<br>
<br>
<br>
Let's <b>go</b>!
</h2>
</section>
<section>
<section>
<h2>Transform: GTUG -> GDG</h2>
Each <br>
<img src="assets/images/gtug_krakow.png" alt="kraków gtug"> Member
<br>
<br>
is now a:
<br>
<img src="assets/images/gdg_krakow_lq.png" alt="GDG Kraków"> Member
</section>
<section>
<h2>Vanilla Java</h2>
<pre><code contenteditable class="java">
List<GTUGMember> gtugMembers = new ArrayList <GTUGMember>();
gtugMembers.add(GTUG.member("Konrad"));
gtugMembers.add(GTUG.member("Łukasz"));
List<GDGMember> gdgMembers = new ArrayList <>();
for(GTUGMember member: gtugMembers)
gdgMembers.add(GDGMember.from(member))
// done!
</code></pre>
</section>
<section>
<h2>Transform</h2>
<pre><code contenteditable class="java">import com.google.common.collect.*;
List<GTUGMember> gtugMembers = Lists.newArrayList(GTUG.member("Konrad"), GTUG.member("Łukasz"));
Function<GTUGMember, GDGMember> toGDGMember = new Function<GTUGMember, GDGMember>() {
@Override
public Object apply(@Nullable String input) {
return input.toUpperCase();
}
};
List<GDGMember> gdgMembers = Lists.transform(gtugMembers, toGDGMember);
</code></pre>
</section>
<section>
<h2>Transform</h2>
A small trick:
<pre><code contenteditable class="java">import com.google.common.collect.*;
class DGDMember {
public static Function<GTUGMember, GDGMember> fromGTUGMember() { /* ... */ }
}
List<GTUGMember> gtugMembers = Lists.newArrayList(GTUG.member("Konrad"), GTUG.member("Łukasz"));
List<GDGMember> gdgMembers = Lists.transform(gtugMembers, GDGMember.fromGTUGMember());
</code></pre>
</section>
<section>
<h2>Transform is a <b>view</b></h2>
<pre><code class="java">List<Integer> integers = newArrayList(1, 2, 3);
List<String> strings = Lists.transform(integers, Functions.toStringFunction());
integers.add(4);
integers.add(5);
assertThat(strings.size()).isEqualTo(5);</code></pre>
</section>
<section>
<h2 style="font-size: 1.5em">"This would be 1 line in _____"</h2>
Scala for example:
<pre><code contenteditable class="scala">
case class GTUGMember(val name: String)
case class GDGMember(val name: String)
val gtugMembers = List(GTUGMember("Konrad"))
// map all members to gdg Members
val gdgMembers = members map { GDGMember(_.name) }
</code></pre>
So, yes - we're aware such things are Simple in other languages, but that's where Guava tries to help.
<br>
<br>
<div class="fragment">
And anyway... <b>LISP</b> had those for years ;-)
</div>
</section>
<section>
<h2>FluentIterable</h2>
A nice new way (since Guava 12) to combine all these operations using a fluent interfaceL
<pre><code class="java" contenteditable>
FluentIterable
.from(database.getClientList())
.filter(activeInLastMonth())
.transform(Functions.toStringFunction())
.limit(10)
.toImmutableList();
</code></pre>
</section>
</section>
<section>
<section>
<h2>Functional concepts brought to Java</h2>
Many things in Guava are inspired by <strong>functional</strong> concepts from <em>other programming lanugages</em>,
just like the previous "map operation" (<b>.transform()</b>)!
</section>
<section>
<h2>Core concepts</h2>
Some of the key functional concepts Guava uses are:
<ul>
<li class="fragment">Function<A,B> == <span class="code">A => B</span></li>
<li class="fragment">Predicate<T> == <span class="code">T => Boolean</span></li>
<li class="fragment">Optional<T> == "<span class="code">Present</span>" or "<span class="code">Absent</span>"</li>
</ul>
<br>
<br>
<div class="fragment"><span class="code">Optional</span> may seem similiar to a "<span class="code">Maybe Monad</span>" :-)</div>
</section>
<section>
<h2>Function <A,B></h2>
Java7 doesn't have lambda expressions, but Guava helps us out (a bit) with <b>Function</b>.
Composing functions:
<pre><code class="java">
Function <Integer, Integer> doubler = new Function <Integer, Integer>() {
@Override
public Integer apply(@Nullable Integer input) {
return input * 2;
}
};
Function<Integer, Integer> halfer = new Function<Integer, Integer>() {
@Override
public Integer apply(@Nullable Integer input) {
return input / 2;
}
};
Function<Integer, Integer> identity = Functions.compose(doubler, halfer);
Integer two = identity.apply(2);
assertThat(two).isEqualTo(2);</code></pre>
<span class="code fragment">doubler(halfer(x))</span>
</section>
<section>
<h2>Optional vs. <span class="code">null</span></h2>
<blockquote class="fragment" cite="http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained">
Null Sucks.
-- Doug Lea
</blockquote>
<br>
<br>
<div class="fragment">
<span class="code">null </span> is "<em>hidden</em>",<br>
<span class="code">Optional</span> is <b>explicit</b>.
</div>
</section>
<section>
<h2>Optional</h2>
<div class="">
Ugly but <span class="code">null</span>-safe:
<pre><code class="java">
public String fullName(String firstName,
Optional<String> maybeMiddleName,
String lastName) {
String middleName = "";
if(maybeMiddleName.isPresent()) {middleName = maybeMiddleName.get();}
return firstName + " " + middleName + " " + lastName;
}</code></pre>
</div>
<div class="fragment">
Nicer:
<pre><code class="java">
public String fullName(String firstName,
Optional<String> maybeMiddleName,
String lastName) {
return firstName + " " + maybeMiddleName.or("") + " " + lastName;
}
</code></pre>
</div>
<blockquote class="fragment">
Haven't seen a null-pointer in my code since a few months now! -- random Optional user
</blockquote>
</section>
<section>
<h2>Predicate</h2>
Quite similar to Function but does <em>NOT</em> extend it.
<pre><code class="java">Predicate<User> onlyAwesome = new Predicate<User>() {
@Override
public boolean apply(@Nullable User in) {
return Optional.fromNullable(in).or(User.NOT_AWESOME).isAwesome();
}
}</code></pre>
<div class="fragment">
Let's use it on a collection:
<pre><code class="java">List<User> users = getMixedUsers();
// find all awesome users
List<User> onlyAwesomeUsers = Iterables.filter(users, onlyAwesome);
</code></pre>
<pre class="fragment"><code class="java">// find one (first) awesome user
User awesomeUser = Iterables.find(users, onlyAwesome);
// or better:
Optional<User> awesomeOrAbsent = Iterables.tryFind(users, onlyAwesome);</code></pre>
</div>
</section>
<section>
<h2>Iterables.*</h2>
Iterables has a lot useful static methods:
<ul>
<li class="code fragment"><T> T get(Iterable<? extends T> iterable, int position, T defaultValue) </li>
<li class="code fragment"><T> Iterable <List<T>> partition(Iterable<T> iterable, int size) </li>
<li class="code fragment"><T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate) </li>
<li class="code fragment"><T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate) </li>
<li class="code fragment"><T> Iterable<T> cycle(<T>... elements)</li>
<li class="fragment">and a lot more!</li>
</ul>
</section>
<section>
<h2>Pro Tip: Function.forMap()</h2>
In Scala for example, a Map behaves just like a Function:
<pre><code class="scala" contenteditable>val nicknameOf = Map("Konrad" -> "ktoso")
nicknameOf("Konrad") == "ktoso"</code></pre>
<div class="fragment">
With Guava's help you can do the same:
<pre><code class="java" contenteditable>ImmutableMap <String, String> nicknameMap = ImmutableMap.of("Konrad", "ktoso");
Function <String, String> nicknameOf = Functions.forMap(nicknameMap);
nicknameOf.apply("Konrad");</code></pre>
If you think about it, a Map is just a function with a <abbr title="Look Up Table">LUT</abbr>.
</div>
<br>
<div class="fragment">"Hey, what's this <b>ImmutableMap</b>?!"</div>
</section>
</section>
<section>
<section>
<h2>Immutability</h2>
Is <strong>awesome</strong> because:
<ul>
<li>
free <strong>thread safety</strong>
</li>
<li>
No more "will someone change this collection?" panic
</li>
<li>
sometimes -> <em>performance</em>
</li>
</ul>
</section>
<section>
<h2>Vanilla JDK - constant set</h2>
<pre><code contenteditable class="java">public static final Set<Integer> NUMS = Collections.unmodifiableSet(
new LinkedHashSet<>(
Arrays.asList(1, 2, 3, 4, 5, 6)
)
);</code></pre>
Problems here?
<ul>
<li class="fragment">3 external classes to build a Set?!</li>
<li class="fragment">Not here but in general: <strong>Umodifiable != Immutable</strong>!</li>
</ul>
</section>
<section>
<h2>ImmutableSet</h2>
<pre><code class="java" contenteditable>public static final Set<Integer> NUMS = ImmutableSet.of(1, 2, 3, 4, 5);
</code></pre>
<div>
<div>Better now?</div>
<ul>
<li class="fragment">Guaranteed immutability</li>
<li class="fragment">FAST</li>
<li class="fragment">SMALL</li>
</ul>
</div>
<span class="fragment">
<small>Highly recommended to check out it's sources - lot's of smart optimizations down there!</small>
</span>
</section>
<section>
<h2>Defensive copying</h2>
<pre><code class="java"contenteditable>
public static final ImmutableSet <Color> GOOGLE_COLORS =
ImmutableSet.<Color>builder()
.addAll(WEBSAFE_COLORS)
.add(new Color(0, 191, 255))
.build();
</code></pre>
</section>
<section>
<h2>More immutable collections</h2>
<small>
<ul>
<li>DescendingImmutableSortedMultiset </li>
<li>ForwardingImmutableList </li>
<li>ForwardingImmutableMap </li>
<li>ForwardingImmutableSet </li>
<li>ImmutableAsList </li>
<li>ImmutableBiMap </li>
<li>ImmutableClassToInstanceMap </li>
<li>ImmutableCollection </li>
<li>ImmutableEntry </li>
<li>ImmutableEnumSet </li>
<li>ImmutableList </li>
<li>ImmutableListMultimap </li>
<li>ImmutableMap </li>
<li>ImmutableMultimap </li>
<li>ImmutableMultiset </li>
<li>ImmutableSet </li>
<li>ImmutableSetMultimap </li>
<li>ImmutableSortedAsList </li>
<li>ImmutableSortedMap </li>
<li>ImmutableSortedMapFauxverideShim </li>
<li>ImmutableSortedMultiset </li>
<li>ImmutableSortedMultisetFauxverideShim </li>
<li>ImmutableSortedSet </li>
<li>ImmutableSortedSetFauxverideShim </li>
<li>ImmutableTable </li>
<li>SingletonImmutableTable </li>
<li>TransformedImmutableSet </li>
<li>... and a lot more ;-)</li>
</ul>
</small>
</section>
</section>
<section>
<section>
<h2>More Collection utils</h2>
<div> A pair of:</div>
<ul>
<li>Joiner</li>
<li>Splitter</li>
</ul>
</section>
<section>
<h2>Joiner</h2>
Solves the issue of nicely printing a list of something.
<div class="fragment">
Sounds easy? Dig this:
<pre><code class="java">List <String> l = newArrayList("a", "b", "c");
String separator = ", ";
StringBuilder sb = new StringBuilder();
String sep = "";
for (Object object : l) {
sb.append(sep).append(object.toString());
sep = separator;
}
assertThat(sb.toString()).isEqualTo("a,b,c");</code></pre>
</div>
<div class="fragment">
Versus this:
<pre><code class="java">String pretty = Joiner.on(", ").join(list);
assertThat(pretty).isEqualTo("a,b,c");</code></pre>
</div>
</section>
<section>
<h2>MapJoiner</h2>
This time without the "without libraries" example, guess why ;-)
<pre><code class="java">Map names = ImmutableMap.of("Konrad", "ktoso", "Sebastian", "fridek");
String s = Joiner.on(";").withKeyValueSeparator(":").join(names);
assertThat(s).isEqualTo("Konrad:ktoso,Sebastian:fridek");</code></pre>
</section>
<section>
<h2>Splitter</h2>
The inverse of <span class="code">Joiner</span>.
<pre><code class="java">
Map<String, String> vals = Splitter.on(';')
.omitEmptyStrings()
.trimResults()
.withKeyValueSeparator(":")
.split(s);
String nickname = vals.get("Konrad");
assertThat(nickname).isEqualTo("ktoso");</code></pre>
<div class="fragment">Yes, <span class="code">Joiner</span> has those <i>nice-to-have </i> methods too.</div>
</section>
<section>
<h2>BiMap</h2>
While we're on a roll here... Let's check out a new Collection class implemented in Guava!
<pre><code class="java">Map<String, String> vals = Splitter.on(';')
.omitEmptyStrings()
.trimResults()
.withKeyValueSeparator(":")
.split(s);
BiMap<String, String> biMap = HashBiMap.create(vals);
String ktoso = biMap.get("Konrad");
String konrad = biMap.inverse().get("ktoso");
</code></pre>
</section>
<section>
<h2>Notable collections</h2>
<ul>
<li>Multiset <String></li>
<li>MultiMap <Integer, String></li>
<li>Table <String, String, Integer></li>
</ul>
</section>
</section>
<section>
<section>
<h2>Streams & Files</h2>
IO Operations are a bit bloated in java (6):
<pre class="fragment"><code class="java"> try {
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
out.close();
} catch (Exception ex) {
logger.error("Unable to hello world! AAAA!", ex);
} finally {
try {
if(out != null) out.close();
} catch(Exception ex) {
logger.error("Unable to close writer! AAAA!!", ex);
}
}
</code></pre>
<div class="fragment">
It's gotten better with <b>Java 7</b>'s try-with-resources:
<pre><code class="java">try(BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"))) {
out.write("Hello Java 7!");
}</code></pre>
</div>
</section>
<section>
<h2>Files</h2>
Guava on the other hand contains such nice methods as:
<pre><code class="java">Files.write("Hello Guava!", new File(""), Charsets.UTF_8);
Files.append("Hello Guava!", new File(""), Charsets.UTF_8);
</code></pre>
<div class="fragment">
We also get some File operation utils (which are kind-of replaced by Java 7's <span class="code"><a
href="http://www.java7developer.com/blog/?p=334">Paths</a></span> nowadays):
<pre><code class="java">Files.move(fromFile, toFile);
Files.touch(new File("/tmp/it.txt"));
// and others:
Files.toString(file, Charsets.UTF_16);
Files.equal(someFile, anotherFile);
</code></pre>
</div>
</section>
<section>
<h2>Closeables</h2>
Yet another way to close streams:
<pre><code class="java">public void useStreamNicely() throws IOException {
SomeStream stream = new SomeStream("foo");
boolean threw = true;
try {
// Some code which does something with the Stream. May throw a
// Throwable.
threw = false; // No throwable thrown.
} finally {
// Close the stream.
// If an exception occurs, only rethrow it if (threw==false).
Closeables.close(stream, threw);
}
</code></pre>
</section>
<!--<section>-->
<!--<h2>Resources</h2>-->
<!--A nice utility class for dealing with... Resources ;-)-->
<!--<div class="fragment">-->
<!--Shortest possible GET request in Java:-->
<!--<pre><code class="java">String myIp = Resources.toString(new URL("http://ip.appspot.com"), Charsets.UTF_8);-->
<!--System.out.println(myIp)</code></pre>-->
<!--Although it's primarily targeted at Classpath Resources ;-)-->
<!--<pre><code class="java">-->
<!--URL resourceUrl = Resources.getResource("config.properties");-->
<!---->
<!--</code></pre>-->
<!--</div>-->
<!--</section>-->
<section>
<h2>Others include...</h2>
<ul>
<li class="fragment">CharStreams</li>
<li class="fragment">ByteStreams</li>
<li class="fragment">NullOutputStream</li>
<li class="fragment">...</li>
</ul>
</section>
</section>
<section>
<section>
<h2>Future</h2>
JDK future is quite ok, but...
<pre class="fragment"><code class="java" contenteditable="">Future <String> futureString = executor.submit(new Callable <String>() {
public String call() { return searcher.search(target); }
});
futureString.get(); // only way to obtain the future!</code></pre>
<div class="fragment">There is <b>FutureTask</b> if you need more...
<br>
Idea: why not have add a <b>listener</b>?</div>
<pre class="fragment"><code class="java" contenteditable="">final ListenableFuture <String> future = service.query(name);
future.addListener(new Runnable() {
public void run() {
logger.info("Yay! Got: " + future.get());
}
}, executor);</code></pre>
</section>
<section>
<h2>Futures</h2>
Futures can also help out with centralizing exception handling:
<br>
<b><a
href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/Futures.html#addCallback(com.google.common.util.concurrent.ListenableFuture, com.google.common.util.concurrent.FutureCallback)">Futures</a></b> can help us out there:
<pre class="fragment"><code class="java">
ListenableFuture <QueryResult> future = ...;
addCallback(future,
new FutureCallback <QueryResult> {
public void onSuccess(QueryResult result) {
storeInCache(result);
}
public void onFailure(Throwable t) {
reportError(t);
}
});
</code></pre>
</section>
<section>
<h2>Treating <b>Future</b> as a Monad</h2>
Hard words, simple code:
<pre class="fragment"><code class="java">
ListenableFuture <QueryResult> future = ...;
Function <QueryResult, URI> mapToURI = ...;
ListenableFuture<URI> futureUri = Futures.transform(future, mapToURI);
</code></pre>
<div class="fragment">
<small>
See how this is "the same" operation as on a collection? It's map / flatMap all over again!
</small>
</div>
</section>
<section>
<h2>More Futures tools</h2>
Since we mentioned collections...
<br>
<em>Transform a <b>List of Futures</b> into a <b>Future List</b></em>
<pre class="fragment"><code class="java" contenteditable="">List <Future <String>> futures = ImmutableList.of(future1, future2);
Future <List <String>> oneFuture = Futures.allAsList(futures);
// ^ succeeds if ALL succeed
</code></pre>
<div class="fragment">
Or just successful futures:
<pre><code class="java">Future <List <String>> oneFuture = Futures.successfulAsList(futures);</code></pre>
</div>
</section>
<section>
<h2>SettableFuture</h2>
A very easy to complete Future implementation:
<pre><code class="java">final SettableFuture<String> future = SettableFuture.create();
future.addListener(new Runnable() {
@Override
public void run() {
try {
String value = future.get();
System.out.println("value = " + value);
} catch (Exception e) {
Throwables.propagate(e);
}
}
}, Executors.newSingleThreadExecutor());</code></pre>
<pre class="fragment"><code class="java">new Thread(){
@Override
public void run() {
try {
Thread.sleep(1000);
future.set("Hello!");
} catch (InterruptedException ignored) { }
}
}.start();</code></pre>
</section>
</section>
<section>
<section>
<h2>Stuff we didn't cover <br>in our 30 minutes</h2>
<ul>
<li class="fragment">@VisibleForTesting</li>
<li class="fragment">TypeToken</li>
<li class="fragment">ForwardingList</li>
<li class="fragment">Hashing</li>
<li class="fragment">UnsignedLong</li>
<li class="fragment">Objects</li>
<li class="fragment">Preconditions</li>
<li class="fragment">MapMaker</li>
<li class="fragment">Stopwatch</li>
<li class="fragment">Limiters</li>
<li class="fragment">... and More!</li>
</ul>
</section>
<section>
<h2>@VisibleForTesting</h2>
A small, <b>nothing-doing</b> annotation.
<pre><code class="java">@VisibleForTesting
List<Stuff> findStuff(String name) {
//...
}</code></pre>
<div class="fragment">It explains why this method is <em>package private</em>. May be "nothing", but is still nice.</div>
</section>
<section>
<h2>TypeToken</h2>
Awesomely <strong>retain generics information in runtime</strong>:
<pre><code contenteditable class="java"> new TypeToken<List<String>>() {}</code></pre>
Without a TypeToken, information about <String> would be lost.
<div class="fragment">
TypeToken leverages the fact that the generics information here MUST be kept in order
to create a class instance of such type.</div>
</section>
<section>
<h2>UnsignedLong</h2>
<div class="fragment">uint in Java!?</div>
<div class="fragment">
<pre><code class="java" contenteditable>
</code></pre>
</div>
</section>
<section>
<h2>Hashing</h2>
Multiple populat hash functions are implemented in it (sha, md5, others...):
<pre><code contenteditable class="java">
Hashing.md5().newHasher()
.putString(name)
.putInt(age)
.hash().asLong();</code></pre>
</section>
<section>
<h2>Objects::equals</h2>
<pre><code class="java">@Override
public boolean equals(Object o) {
Person that = (Person) o;
if (age != null ? !age.equals(person.age) : person.age != null) return false;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
return true;
}</code></pre>
Vs.
<pre class="fragment"><code class="java">@Override
public boolean equals(Object o) {
Person that = (Person) o;
return Objects.equal(that.name, this.name) && Objects.equal(that.age, this.age);
}</code></pre>
<div class="fragment">Pro Tip: A similar implementation is present in <b>JDK7</b>! :-)</div>
</section>
<section>
<h2>Objects::hashCode</h2>
<pre><code class="java">@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (surname != null ? surname.hashCode() : 0);
result = 31 * result + (age != null ? age.hashCode() : 0);
return result;
}</code></pre>
Vs.
<pre class="fragment"><code class="java">@Override
public int hashCode() {
return Objects.hashCode(name, surname, age);
}</code></pre>
<div class="fragment">
Pro Tip: <span class="code">java.util.Objects::hash(Object... objects)</span> has also been implemented in
<b>JDK7</b>!
</div>
</section>
<section>
<h2>Itermission: Why "::"?</h2>
<div>As <b>JDK 8</b> is comming nearer... let's get confortable with the <span class="code">Class::method</span>
notation.</div>
<div class="fragment">
As of JDK 8, this syntax will be used to obtain <b>Method references</b>:
<pre><code class="java">class Person {
public String get() { return "" }
}
String::toString;
// or
Person p = new Person();
p::get;
</code></pre>
<a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html" class="right">...java.net/~briangoetz/lambda/lambda-state-4.html</a>
</div>
</section>
<section>
<h2>Intermission: Why "::"?</h2>
Why should you care?
<br>
<br>
<pre><code class="java" contenteditable="">// bellow code is valid (JDK 8) Java
Collections.sort(people, comparing(p -> p.getLastName()));
people.sort(comparing(Person::getLastName));
</code></pre>
The Guava equivalent (a bit more powerfull):
<pre class="fragment"><code class="java" contenteditable>
List <Foo> foos = newArrayList(new Foo("z"), new Foo("a"));
Function <Foo, Comparable> getName = new Function <Foo, Comparable>() {
public Comparable apply(@Nullable Foo input) {
assert input != null;
return input.name;
}
};
Collections.sort(foos, Ordering.natural().onResultOf(getName));
</code></pre>
<div class="fragment">
Mini Scala trolling:
<pre ><code class="scala">
foos.sortBy(_.name)
</code></pre>
</div>
</section>
<section>
<h2>MapMaker</h2>
<pre><code class="java">
ConcurrentMap<Key, Graph> graphs = new MapMaker()
.concurrencyLevel(4)
.makeComputingMap(
new Function<Key, Graph>() {
public Graph apply(Key key) {
return createExpensiveGraph(key);
}
});
</code></pre>
</section>
<section>
<h2>MapMaker</h2>
<pre><code class="java">
ConcurrentMap<Key, Graph> graphs = new MapMaker()
.concurrencyLevel(4)
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.makeComputingMap(
new Function<Key, Graph>() {
public Graph apply(Key key) {
return createExpensiveGraph(key);
}
});
</code></pre>