forked from ashishjohn1908/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambdaexpressions.html
More file actions
1261 lines (1044 loc) · 53.2 KB
/
Copy pathlambdaexpressions.html
File metadata and controls
1261 lines (1044 loc) · 53.2 KB
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
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Lambda Expressions (The Java™ Tutorials >
Learning the Java Language > Classes and Objects)
</title>
<meta name="description" content="This beginner Java tutorial describes fundamentals of programming in the Java programming language" />
<meta name="keywords" content="java programming, learn java, java sample code, java objects, java classes, java inheritance, interfaces, variables, arrays, data types, operators, control flow, number, string" />
<style type="text/css">
.FigureCaption {
margin-left: 1in;
margin-right: 1in;
font-family: sans-serif;
font-size: smaller;
text-align: justify;
}
#TopBar_bl {
background: url(../../images/java_bar_bl.gif) 0 100% no-repeat;
width: 100%;
height: 60px;
}
#TopBar_br {
background: url(../../images/java_bar_br.gif) 100% 100% no-repeat;
width: 100%;
height: 60px;
}
#TopBar_tl {
background: url(../../images/java_bar_tl.gif) 0 0 no-repeat;
width: 100%;
height: 60px;
}
#TopBar_tr {
background: url(../../images/java_bar_tr.gif) 100% 0 no-repeat;
width: 100%;
height: 60px;
}
#TopBar {
background: #35556B url(../../images/java_bar.gif);
margin: 10px 10px 0 10px;
height:60px;
min-width:700px;
color: white;
font-family: sans-serif;
font-weight: bold;
}
@media print {
#BreadCrumbs, #Download {
display: none;
}
}
#TopBar_right {
line-height: 14px;
float: right;
padding-top: 2px;
padding-right: 30px;
text-align: left;
}
@media print {
#TopBar_right {
display: none;
}
}
#TopBar_right a {
font-size: 12px;
margin: 3px;
padding: 0;
}
#TopBar a:visited, #TopBar a:link {
color: white;
text-decoration: none;
}
#TopBar a:hover, #TopBar a:active {
background-color: white;
color: #35556B;
}
#BreadCrumbs {
padding: 4px 5px 0.5em 0;
font-family: sans-serif;
float: right;
}
#BreadCrumbs a {
color: blue;
}
#BreadCrumbs a:visited, #BreadCrumbs a:link {
text-decoration: none;
}
#BreadCrumbs a:hover, #BreadCrumbs a:active {
text-decoration: underline;
}
#PageTitle {
margin: 0 5px 0.5em 0;
color: #F90000;
}
#PageContent{
margin: 0 5px 0 20px;
}
.LeftBar_shown {
width: 13em;
float: left;
margin-left: 10px;
margin-top: 4px;
margin-bottom: 2em;
margin-right: 10px;
}
@media print {
.LeftBar_shown {
display: none;
}
}
.LeftBar_hidden {
display: none;
}
#Footer {
padding-top: 10px;
padding-left: 10px;
margin-right: 10px;
}
.footertext {
font-size: 10px;
font-family: sans-serif;
margin-top: 1px;
}
#Footer2 {
padding-top: 10px;
padding-left: 10px;
margin-right: 10px;
}
.NavBit {
padding: 4px 5px 0.5em 0;
font-family: sans-serif;
}
@media print {
.NavBit {
display: none;
}
}
#TagNotes {
text-align: right;
}
@media print {
#TagNotes a:visited, #TagNotes a:link {
color: #35556B;
text-decoration: none;
}
}
#Contents a, .NavBit a, #TagNotes a {
color: blue
}
#TagNotes a:visited, #TagNotes a:link,
#Contents a:visited, #Contents a:link,
.NavBit a:visited, .NavBit a:link {
text-decoration: none;
}
#TagNotes a:hover, #TagNotes a:active,
#Contents a:hover, #Contents a:active,
.NavBit a:hover, .NavBit a:active {
text-decoration: underline;
}
#Contents {
float: left;
font-family: sans-serif;
}
@media print {
#Contents {
display: none;
}
}
@media screen {
div.PrintHeaders {
display: none;
}
}
.linkLESSON, .nolinkLESSON {
margin-left: 0.5em;
text-indent: -0.5em
}
.linkAHEAD, .nolinkAHEAD, .linkQUESTIONS, .nolinkQUESTIONS {
margin-left: 1.5em;
text-indent: -0.5em
}
.linkBHEAD, .nolinkBHEAD {
margin-left: 2.5em;
text-indent: -0.5em
}
.linkCHEAD, .nolinkCHEAD {
margin-left: 3.5em;
text-indent: -0.5em
}
.nolinkLESSON, .nolinkAHEAD, .nolinkBHEAD, .nolinkCHEAD,
.nolinkQUESTIONS {
font-weight: bold;
color: #F90000;
}
.MainFlow_indented {
margin-right: 10px;
margin-left: 15em;
margin-bottom: 2em;
}
.MainFlow_wide {
margin-right: 10px;
margin-left: 10px;
margin-bottom: 2em;
}
@media print {
.MainFlow_indented, .MainFlow_wide {
padding-top: 0;
margin-top: 10px;
margin-right: 10px;
margin-left: 0;
}
}
h1, h2, h3, h4, h5 {
color: #F90000;
font-family: sans-serif;
}
h1 {
font-weight: bold;
font-size: 20px;
}
h2 {
font-weight: bold;
font-size: 17px;
}
h3 {
font-weight: bold;
font-size: 14px;
}
h4 {
font-size: 15px;
}
h5 {
font-size: 12px;
}
#ToggleLeft {
display: none;
}
.note {
margin: 0 30px 0px 30px;
}
.codeblock {
margin: 0 30px 0px 30px;
}
.tocli {
list-style-type:none;
}
.betadraft {
color: red;
}
</style>
<script type="text/javascript">
/* <![CDATA[ */
function leftBar() {
var nameq = 'tutorial_showLeftBar='
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookieString = cookies[i];
while (cookieString.charAt(0) == ' ') {
cookieString = cookieString.substring(1, cookieString.length);
}
if (cookieString.indexOf(nameq) == 0) {
cookieValue = cookieString.substring(nameq.length,
cookieString.length);
return cookieValue == 'yes';
}
}
return true;
}
function showLeft(b) {
var contents = document.getElementById("LeftBar");
var main = document.getElementById("MainFlow");
var toggle = document.getElementById("ToggleLeft");
if (b) {
contents.className = "LeftBar_shown";
main.className = "MainFlow_indented";
toggle.innerHTML = "Hide TOC";
document.cookie = 'tutorial_showLeftBar=yes; path=/';
} else {
contents.className = "LeftBar_hidden";
main.className = "MainFlow_wide";
toggle.innerHTML = "Show the TOC";
document.cookie = 'tutorial_showLeftBar=no; path=/';
}
}
function toggleLeft() {
showLeft(document.getElementById("LeftBar").className ==
"LeftBar_hidden");
document.getElementById("ToggleLeft").blur();
}
function load() {
showLeft(leftBar());
document.getElementById("ToggleLeft").style.display="inline";
}
function showCode(displayCodePage, codePath) {
var codePathEls = codePath.split("/");
var currDocPathEls = location.href.split("/");
//alert ("codePathEls = " + codePathEls + "\n" + "currDocPathEls = " + currDocPathEls);
currDocPathEls.pop(); // remove file name at the end
while (codePathEls.length > 0) {
if (codePathEls[0] == "..") {
codePathEls.shift();
currDocPathEls.pop();
} else {
break;
}
}
var fullCodePath = currDocPathEls.join("/") + "/" + codePathEls.join("/");
//alert ("fullCodePath = " + fullCodePath );
if (codePath.indexOf(".java") != -1 || codePath.indexOf(".jnlp") != -1) {
window.location.href = displayCodePage + "?code=" + encodeURI(fullCodePath);
} else {
window.location.href = fullCodePath;
}
}
/* ]]> */
</script>
</head>
<body onload="load()">
<noscript>
A browser with JavaScript enabled is required for this page to operate properly.
</noscript>
<div id="TopBar"> <div id="TopBar_tr"> <div id="TopBar_tl"> <div id="TopBar_br"> <div id="TopBar_bl">
<div id="TopBar_right">
<a target="_blank"
href="http://www.oracle.com/technetwork/java/javase/downloads/java-se-7-tutorial-2012-02-28-1536013.html">Download Ebooks</a><br />
<a target="_blank"
href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">Download JDK</a>
<br />
<a href="../../search.html" target="_blank">Search Java Tutorials</a>
<br />
<a href="javascript:toggleLeft()"
id="ToggleLeft">Hide TOC</a>
</div>
</div> </div> </div> </div> </div>
<div class="PrintHeaders">
<b>Trail:</b> Learning the Java Language
<br /><b>Lesson:</b> Classes and Objects
<br /><b>Section:</b> Nested Classes
</div>
<div id="LeftBar" class="LeftBar_shown">
<div id="Contents">
<div class="linkLESSON"><a href="index.html">Classes and Objects</a></div>
<div class="linkAHEAD"><a href="classes.html">Classes</a></div>
<div class="linkBHEAD"><a href="classdecl.html">Declaring Classes</a></div>
<div class="linkBHEAD"><a href="variables.html">Declaring Member Variables</a></div>
<div class="linkBHEAD"><a href="methods.html">Defining Methods</a></div>
<div class="linkBHEAD"><a href="constructors.html">Providing Constructors for Your Classes</a></div>
<div class="linkBHEAD"><a href="arguments.html">Passing Information to a Method or a Constructor</a></div>
<div class="linkAHEAD"><a href="objects.html">Objects</a></div>
<div class="linkBHEAD"><a href="objectcreation.html">Creating Objects</a></div>
<div class="linkBHEAD"><a href="usingobject.html">Using Objects</a></div>
<div class="linkAHEAD"><a href="more.html">More on Classes</a></div>
<div class="linkBHEAD"><a href="returnvalue.html">Returning a Value from a Method</a></div>
<div class="linkBHEAD"><a href="thiskey.html">Using the this Keyword</a></div>
<div class="linkBHEAD"><a href="accesscontrol.html">Controlling Access to Members of a Class</a></div>
<div class="linkBHEAD"><a href="classvars.html">Understanding Class Members</a></div>
<div class="linkBHEAD"><a href="initial.html">Initializing Fields</a></div>
<div class="linkBHEAD"><a href="summaryclasses.html">Summary of Creating and Using Classes and Objects</a></div>
<div class="linkQUESTIONS"><a href="QandE/creating-questions.html">Questions and Exercises</a></div>
<div class="linkQUESTIONS"><a href="QandE/objects-questions.html">Questions and Exercises</a></div>
<div class="linkAHEAD"><a href="nested.html">Nested Classes</a></div>
<div class="linkBHEAD"><a href="innerclasses.html">Inner Class Example</a></div>
<div class="linkBHEAD"><a href="localclasses.html">Local Classes</a></div>
<div class="linkBHEAD"><a href="anonymousclasses.html">Anonymous Classes</a></div>
<div class="nolinkBHEAD">Lambda Expressions</div>
<div class="linkCHEAD"><a href="methodreferences.html">Method References</a></div>
<div class="linkBHEAD"><a href="whentouse.html">When to Use Nested Classes, Local Classes, Anonymous Classes, and Lambda Expressions </a></div>
<div class="linkQUESTIONS"><a href="QandE/nested-questions.html">Questions and Exercises</a></div>
<div class="linkAHEAD"><a href="enum.html">Enum Types</a></div>
<div class="linkQUESTIONS"><a href="QandE/enum-questions.html">Questions and Exercises</a></div>
</div>
</div>
<div id="MainFlow" class="MainFlow_indented">
<span id="BreadCrumbs">
<a href="../../index.html" target="_top">Home Page</a>
>
<a href="../index.html" target="_top">Learning the Java Language</a>
>
<a href="index.html" target="_top">Classes and Objects</a>
</span>
<div class="NavBit">
<a target="_top" href="anonymousclasses.html">« Previous</a> • <a target="_top" href="../TOC.html">Trail</a> • <a target="_top" href="methodreferences.html">Next »</a>
</div>
<div id="PageTitle"><h1>Lambda Expressions</h1></div>
<div id="PageContent">
<p>One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.</p>
<p>The previous section,
<a class="TutorialLink" target="_top" href="anonymousclasses.html">Anonymous Classes</a>, shows you how to implement a base class without giving it a name.
Although this is often more concise than a named class, for classes
with only one method, even an anonymous class seems a bit
excessive and cumbersome. Lambda expressions let you express instances of
single-method classes more compactly.</p>
<p>This section covers the following topics:</p>
<ul>
<li><a href="#use-case">Ideal Use Case for Lambda Expressions</a>
<ul>
<li><a href="#approach1">Approach 1: Create Methods That Search for Members That Match One Characteristic</a></li>
<li><a href="#approach2">Approach 2: Create More Generalized Search Methods</a></li>
<li><a href="#approach3">Approach 3: Specify Search Criteria Code in a Local Class</a></li>
<li><a href="#approach4">Approach 4: Specify Search Criteria Code in an Anonymous Class</a></li>
<li><a href="#approach5">Approach 5: Specify Search Criteria Code with a Lambda Expression</a></li>
<li><a href="#approach6">Approach 6: Use Standard Functional Interfaces with Lambda Expressions</a></li>
<li><a href="#approach7">Approach 7: Use Lambda Expressions Throughout Your Application</a></li>
<li><a href="#approach8">Approach 8: Use Generics More Extensively</a></li>
<li><a href="#approach9">Approach 9: Use Aggregate Operations That Accept Lambda Expressions as Parameters</a></li>
</ul>
</li>
<li><a href="#lambda-expressions-in-gui-applications">Lambda Expressions in GUI Applications</a></li>
<li><a href="#syntax">Syntax of Lambda Expressions</a></li>
<li><a href="#accessing-local-variables">Accessing Local Variables of the Enclosing Scope</a></li>
<li><a href="#target-typing">Target Typing</a>
<ul>
<li><a href="#target-types-and-method-arguments">Target Types and Method Arguments</a></li>
</ul>
</li>
<li><a href="#serialization">Serialization</a></li>
</ul>
<h2><a name="use-case">Ideal Use Case for Lambda Expressions</a></h2>
<p>Suppose that you are creating a social networking application. You
want to create a feature that enables an administrator to perform
any kind of action, such as sending a message, on members of the
social networking application that satisfy certain criteria. The following table describes this use case in detail:</p>
<table border="1" summary="Use case for social networking application">
<tr>
<th id="h1">Field</th>
<th id="h2">Description</th>
</tr>
<tr>
<td headers="h1">Name</td>
<td headers="h2">Perform action on selected members</td>
</tr>
<tr>
<td headers="h1">Primary Actor</td>
<td headers="h2">Administrator</td>
</tr>
<tr>
<td headers="h1">Preconditions</td>
<td headers="h2">Administrator is logged in to the system.</td>
</tr>
<tr>
<td headers="h1">Postconditions</td>
<td headers="h2">Action is performed only on members that fit the specified criteria.</td>
</tr>
<tr>
<td headers="h1">Main Success Scenario</td>
<td headers="h2">
<ol>
<li>Administrator specifies criteria of members on which to perform a certain action.</li>
<li>Administrator specifies an action to perform on those selected members.</li>
<li>Administrator selects the <strong>Submit</strong> button.</li>
<li>The system finds all members that match the specified criteria.</li>
<li>The system performs the specified action on all matching members.</li>
</ol>
</td>
</tr>
<tr>
<td headers="h1">Extensions</td>
<td headers="h2">
<p>1a. Administrator has an option to preview those members who match the specified criteria before he or she specifies the action to be performed or before selecting the <strong>Submit</strong> button.</p>
</td>
</tr>
<tr>
<td headers="h1">Frequency of Occurrence</td>
<td headers="h2">Many times during the day.</td>
</tr>
</table>
<p>Suppose that members of this social networking application are
represented by the following
<a class="SourceLink" target="_blank" href="examples/Person.java" onclick="showCode('../../displayCode.html', 'examples/Person.java'); return false;"><code>Person</code></a> class:</p>
<pre class="codeblock">public class Person {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public int getAge() {
// ...
}
public void printPerson() {
// ...
}
}</pre>
<p>Suppose that the members of your social networking application
are stored in a <code>List<Person></code> instance.</p>
<p>This section begins with a naive approach to this use case. It improves upon this approach with local and anonymous classes, and then finishes with an efficient and concise approach using lambda expressions. Find the code excerpts described in this section in the example
<a class="SourceLink" target="_blank" href="examples/RosterTest.java" onclick="showCode('../../displayCode.html', 'examples/RosterTest.java'); return false;"><code>RosterTest</code></a>.
</p>
<h3><a name="approach1">Approach 1: Create Methods That Search for Members That Match One Characteristic</a></h3>
<p>One simplistic approach is to create several methods; each method searches for members that match one characteristic, such as gender or age. The following method prints members that are older than a specified
age:</p>
<pre class="codeblock">public static void printPersonsOlderThan(List<Person> roster, int age) {
for (Person p : roster) {
if (p.getAge() >= age) {
p.printPerson();
}
}
}</pre>
<p><b>Note</b>: A
<a class="APILink" target="_blank" href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html"><code>List</code></a> is an ordered
<a class="APILink" target="_blank" href="http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html"><code>Collection</code></a>. A <em>collection</em> is an object
that groups multiple elements into a single unit. Collections are
used to store, retrieve, manipulate, and communicate aggregate
data. For more information about collections, see the
<a class="TutorialLink" target="_top" href="../../collections/index.html">Collections</a> trail.</p>
<p>This approach can potentially make your application <em>brittle</em>, which is the likelihood of an application not working because of the introduction of updates (such as newer data types). Suppose that you upgrade your application and change the structure of the <code>Person</code> class such that it contains different member variables; perhaps the class records and measures ages with a different data type or algorithm. You would have to rewrite a lot of your API to accommodate this change. In addition, this approach is unnecessarily restrictive; what if you
wanted to print members younger than a certain age, for example?</p>
<!-- ********************************************************************** -->
<h3><a name="approach2">Approach 2: Create More Generalized Search Methods</a></h3>
<p>The following method is more generic than <code>printPersonsOlderThan</code>; it prints members within a specified range of ages:</p>
<pre class="codeblock">public static void printPersonsWithinAgeRange(
List<Person> roster, int low, int high) {
for (Person p : roster) {
if (low <= p.getAge() && p.getAge() < high) {
p.printPerson();
}
}
}</pre>
<p>What if you want to print members of a specified sex, or a combination of a specified gender and age range? What if you decide to change the <code>Person</code> class and add other attributes such as relationship status or geographical location? Although this method is more generic than <code>printPersonsOlderThan</code>, trying to create a separate method for each possible search query can still lead to brittle code. You can instead separate the code that specifies the criteria for which you want to search in a different class.</p>
<!-- ********************************************************************** -->
<h3><a name="approach3">Approach 3: Specify Search Criteria Code in a Local Class</a></h3>
<p>The following method prints members that match search criteria that you specify:</p>
<pre class="codeblock">public static void printPersons(
List<Person> roster, CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}</pre>
<p>This method checks each <code>Person</code> instance contained in the <code>List</code> parameter <code>roster</code> whether it satisfies the search criteria specified in the <code>CheckPerson</code> parameter <code>tester</code> by invoking the method <code>tester.test</code>. If the method <code>tester.test</code> returns a <code>true</code> value, then the method <code>printPersons</code> is invoked on the <code>Person</code> instance.</p>
<p>To specify the search criteria, you implement the
<code>CheckPerson</code> interface:</p>
<pre class="codeblock">interface CheckPerson {
boolean test(Person p);
}</pre>
<p>The following class implements the <code>CheckPerson</code> interface by specifying an implementation for the method <code>test</code>. This method filters members that are eligible for Selective Service in the United States: it returns a <code>true</code> value if its <code>Person</code> parameter is male and between the ages of 18 and 25:</p>
<pre class="codeblock">class CheckPersonEligibleForSelectiveService implements CheckPerson {
public boolean test(Person p) {
return p.gender == Person.Sex.MALE &&
p.getAge() >= 18 &&
p.getAge() <= 25;
}
}</pre>
<p>To use this class, you create a new
instance of it and invoke the <code>printPersons</code> method:</p>
<pre class="codeblock">printPersons(
roster, new CheckPersonEligibleForSelectiveService());</pre>
<p>Although this approach is less brittle—you don't have to rewrite methods if you change the structure of the <code>Person</code>—you still have additional code: a new interface and a local class for each search you plan to perform in your application. Because <code>CheckPersonEligibleForSelectiveService</code>
implements an interface, you can use an anonymous class
instead of a local class and bypass the need to declare a new class for each search.</p>
<!-- ********************************************************************** -->
<h3><a name="approach4">Approach 4: Specify Search Criteria Code in an Anonymous Class</a></h3>
<p>One of the arguments of the following invocation of the method <code>printPersons</code> is an anonymous class that filters members that are eligible for Selective Service in the United States: those who are male and between the ages of 18 and 25:</p>
<pre class="codeblock">printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);</pre>
<p>This approach reduces the amount of code required because you don't have to create a new class for each search that you want to perform. However, the syntax of anonymous classes is bulky considering that the <code>CheckPerson</code> interface contains only one method. In this
case, you can use a lambda expression instead of an anonymous class, as
described in the next section.</p>
<!-- ********************************************************************** -->
<h3><a name="approach5">Approach 5: Specify Search Criteria Code with a Lambda Expression</a></h3>
<p>The <code>CheckPerson</code>
interface is a <i>functional interface</i>. A functional
interface is any interface that contains only one
<a class="TutorialLink" target="_top" href="../../java/IandI/abstract.html">abstract method</a>. (A functional interface may contain one or more
<a class="TutorialLink" target="_top" href="../../java/IandI/defaultmethods.html">default methods</a> or
<a class="TutorialLink" target="_top" href="../../java/IandI/defaultmethods.html#static">static methods</a>.) Because
a functional interface contains only one abstract method, you can
omit the name of that method
when you implement it. To do this, instead of using an anonymous
class expression, you use a <i>lambda
expression</i>, which is
highlighted in the following method invocation:</p>
<pre class="codeblock">printPersons(
roster,
<strong>(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25</strong>
);</pre>
<p>See <a href="#syntax">Syntax of Lambda Expressions</a> for information about how to define lambda expressions.</p>
<p>You can use a standard functional interface in place of the interface <code>CheckPerson</code>, which reduces even further the amount of code required.</p>
<!-- ********************************************************************** -->
<h3><a name="approach6">Approach 6: Use Standard Functional Interfaces with Lambda Expressions</a></h3>
<p>Reconsider the <code>CheckPerson</code> interface:</p>
<pre class="codeblock">interface CheckPerson {
boolean test(Person p);
}</pre>
<p>This is a very
simple interface. It's a functional interface because it contains
only one abstract method. This method takes one parameter and returns a
<code>boolean</code> value. The method is so simple that it might not be worth
it to define one in your application. Consequently, the JDK
defines several standard functional interfaces, which you can
find in the package <code>java.util.function</code>.</p>
<p>For example, you can use the
<code>Predicate<T></code>
interface in place of <code>CheckPerson</code>. This
interface contains the method <code>boolean
test(T t)</code>:</p>
<pre class="codeblock">interface Predicate<T> {
boolean test(T t);
}</pre>
<p>The interface <code>Predicate<T></code> is an example of a generic interface. (For more information about generics, see the
<a class="TutorialLink" target="_top" href="../../java/generics/index.html">Generics (Updated)</a> lesson.) Generic types (such as generic interfaces) specify one or more type parameters within angle brackets (<code><></code>). This interface contains only one type parameter, <code>T</code>. When you declare or instantiate a generic type with actual type arguments, you have a parameterized type. For example, the parameterized type <code>Predicate<Person></code> is the following:</p>
<pre class="codeblock">interface Predicate<<code>Person</code>> {
boolean test(<code>Person</code> t);
}</pre>
<p>This parameterized type contains a method that has the same return type and parameters as <code>CheckPerson.boolean test(Person p)</code>. Consequently, you can use <code>Predicate<T></code> in place of <code>CheckPerson</code> as the following method demonstrates:</p>
<pre class="codeblock">public static void printPersonsWithPredicate(
List<Person> roster, Predicate<Person> tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}</pre>
<p>As a result,
the following method invocation is the same as when you invoked
<code>printPersons</code> in <a href="#approach3">Approach 3: Specify Search Criteria Code in a Local Class</a> to obtain members who are eligible for Selective Service:</p>
<pre class="codeblock">printPersonsWithPredicate(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);</pre>
<p>This is not the only possible place in this method to use a lambda expression. The following approach suggests other ways to use lambda expressions.</p>
<!-- ********************************************************************** -->
<h3><a name="approach7">Approach 7: Use Lambda Expressions Throughout Your Application</a></h3>
<p>Reconsider the method <code>printPersonsWithPredicate</code>
to see where else you could use lambda expressions:</p>
<pre class="codeblock">public static void printPersonsWithPredicate(
List<Person> roster, Predicate<Person> tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}</pre>
<p>This method checks each <code>Person</code> instance contained in the <code>List</code> parameter <code>roster</code> whether it satisfies the criteria specified in the <code>Predicate</code> parameter <code>tester</code>. If the <code>Person</code> instance does satisfy the criteria specified by <code>tester</code>, the method <code>printPersron</code> is invoked on the <code>Person</code> instance.</p>
<p>Instead of invoking the method <code>printPerson</code>, you can specify a different action to perform on those <code>Person</code> instances that satisfy the criteria specified by <code>tester</code>. You can specify this action with a lambda expression. Suppose you want a lambda expression similar to <code>printPerson</code>, one that takes one argument (an object of type <code>Person</code>) and returns void. Remember, to use a lambda expression, you need to implement a functional interface. In this case, you need a functional interface that contains an abstract method that can take one argument of type <code>Person</code> and returns void. The
<code>Consumer<T></code>
interface contains the method
<code>void accept(T t)</code>, which has these characteristics. The
following method replaces the invocation
<code>p.printPerson()</code> with an
instance of <code>Consumer<Person></code> that invokes the method <code>accept</code>:</p>
<pre class="codeblock">public static void processPersons(
List<Person> roster,
Predicate<Person> tester,
<strong>Consumer<Person> block</strong>) {
for (Person p : roster) {
if (tester.test(p)) {
<strong>block.accept(p);</strong>
}
}
}</pre>
<p>As a
result, the following method invocation is the same as when you invoked <code>printPersons</code> in <a href="#approach3">Approach 3: Specify Search Criteria Code in a Local Class</a> to obtain members who are eligible for Selective Service. The lambda expression used to
print members is highlighted:</p>
<pre class="codeblock">processPersons(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25,
<strong>p -> p.printPerson()</strong>
);</pre>
<p>What if you want to do more with your members' profiles than printing them out. Suppose that you want to validate the members' profiles or retrieve
their contact information? In this case, you need a functional
interface that contains an abstract method that returns a value.
The
<code>Function<T,R></code>
interface contains the
method <code>R apply(T
t)</code>. The following method retrieves the data
specified by the parameter <code>mapper</code>, and
then performs an action on it specified by the
parameter <code>block</code>:</p>
<pre class="codeblock">public static void processPersonsWithFunction(
List<Person> roster,
Predicate<Person> tester,
Function<Person, String> mapper,
Consumer<String> block) {
for (Person p : roster) {
if (tester.test(p)) {
String data = mapper.apply(p);
block.accept(data);
}
}
}</pre>
<p>The following method retrieves the email address from each member
contained in <code>roster</code> who are eligible for Selective Service and
then prints it:</p>
<pre class="codeblock">processPersonsWithFunction(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25,
p -> p.getEmailAddress(),
email -> System.out.println(email)
);</pre>
<!-- ********************************************************************** -->
<h3><a name="approach8">Approach 8: Use Generics More Extensively</a></h3>
<p>Reconsider the method <code>processPersonsWithFunction</code>. The following is a generic version of it that accepts, as a parameter, a collection that contains elements of any data type:</p>
<pre class="codeblock">public static <X, Y> void processElements(
Iterable<X> source,
Predicate<X> tester,
Function <X, Y> mapper,
Consumer<Y> block) {
for (X p : source) {
if (tester.test(p)) {
Y data = mapper.apply(p);
block.accept(data);
}
}
}</pre>
<p>To print the e-mail address of members who are eligible for Selective Service, invoke the <code>processElements</code> method as follows:</p>
<pre class="codeblock">processElements(
roster,
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25,
p -> p.getEmailAddress(),
email -> System.out.println(email)
);</pre>
<p>This method invocation performs the following actions:</p>
<ol>
<li>Obtains a source of objects from the collection <code>source</code>. In this example, it obtains a source of <code>Person</code> objects from the collection <code>roster</code>. Notice that the collection <code>roster</code>, which is a collection of type <code>List</code>, is also an object of type <code>Iterable</code>.</li>
<li>Filters objects that match the <code>Predicate</code> object <code>tester</code>. In this example, the <code>Predicate</code> object is a lambda expression that specifies which members would be eligible for Selective Service.</li>
<li>Maps each filtered object to a value as specified by the <code>Function</code> object <code>mapper</code>. In this example, the <code>Function</code> object is a lambda expression that returns the e-mail address of a member.</li>
<li>Performs an action on each mapped object as specified by the <code>Consumer</code> object <code>block</code>. In this example, the <code>Consumer</code> object is a lambda expression that prints a string, which is the e-mail address returned by the <code>Function</code> object.</li>
</ol>
<p>You can replace each of these actions with an aggregate operation.</p>
<!-- ********************************************************************** -->
<h3><a name="approach9">Approach 9: Use Aggregate Operations That Accept Lambda Expressions as Parameters</a></h3>
<p>The following example uses aggregate operations to print the e-mail addresses of those members contained in the collection <code>roster</code> who are eligible for Selective Service:</p>
<pre class="codeblock">roster
.stream()
.filter(
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25)
.map(p -> p.getEmailAddress())
.forEach(email -> System.out.println(email));</pre>
<p>The following table maps each of the operations the method <code>processElements</code> performs with the corresponding aggregate operation:</p>
<table border="1" summary="Mapping of each of the actions the method processElements performs with the corresponding aggregate operation">
<tr>
<th id="h101"><code>processElements</code> Action</th>
<th id="h102">Aggregate Operation</th>
</tr>
<tr>
<td headers="h101">Obtain a source of objects</td>
<td headers="h102"><code>Stream<E> <strong>stream</strong>()</code></td>
</tr>
<tr>
<td headers="h101">Filter objects that match a <code>Predicate</code> object</td>
<td headers="h102"><code>Stream<T> <strong>filter</strong>(Predicate<? super T> predicate)</code></td>
</tr>
<tr>
<td headers="h101">Map objects to another value as specified by a <code>Function</code> object</td>
<td headers="h102"><code><R> Stream<R> <strong>map</strong>(Function<? super T,? extends R> mapper)</code></td>
</tr>
<tr>
<td headers="h101">Perform an action as specified by a <code>Consumer</code> object</td>
<td headers="h102"><code>void <strong>forEach</strong>(Consumer<? super T> action)</code></td>
</tr>
</table>
<p>The operations <code>filter</code>, <code>map</code>, and <code>forEach</code> are <em>aggregate operations</em>. Aggregate operations process elements from a stream, not directly from a collection (which is the reason why the first method invoked in this example is <code>stream</code>). A <em>stream</em> is a sequence of elements. Unlike a collection, it is not a data structure that stores elements. Instead, a stream carries values from a source, such as collection, through a pipeline. A <em>pipeline</em> is a sequence of stream operations, which in this example is <code>filter</code>- <code>map</code>-<code>forEach</code>. In addition, aggregate operations typically accept lambda expressions as parameters, enabling you to customize how they behave.</p>
<p>For a more thorough discussion of aggregate operations, see the
<a class="TutorialLink" target="_top" href="../../collections/streams/index.html">Aggregate Operations</a> lesson.</p>
<h2><a name="lambda-expressions-in-gui-applications">Lambda Expressions in GUI Applications</a></h2>
<p>To process events in a graphical user interface (GUI) application, such as keyboard
actions, mouse actions, and scroll actions, you typically create
event handlers, which usually involves implementing a particular
interface. Often, event handler interfaces are functional
interfaces; they tend to have only one method.</p>
<p>In the JavaFX example <a href=
"http://docs.oracle.com/javafx/2/get_started/hello_world.htm">
<code>HelloWorld.java</code></a> (discussed in the previous section
<a class="TutorialLink" target="_top" href="anonymousclasses.html">Anonymous Classes</a>), you can
replace the highlighted anonymous class with a lambda expression in this
statement:</p>
<pre class="codeblock"> btn.setOnAction(<b>new EventHandler<ActionEvent>() {</b>
<b>@Override</b>
<b>public void handle(ActionEvent event) {</b>
<b>System.out.println("Hello World!");</b>
<b>}</b>
<b>}</b>);</pre>
<p>The method invocation <code>btn.setOnAction</code> specifies what
happens when you select the button represented by the <code>btn</code> object. This method requires
an object of type <code>EventHandler<ActionEvent></code>. The <code>EventHandler<ActionEvent></code>
interface contains only one method, <code>void handle(T event)</code>.
This interface is a functional interface, so you could use the following highlighted lambda expression to replace it:</p>
<pre class="codeblock"> btn.setOnAction(
<b>event -> System.out.println("Hello World!")</b>
);</pre>
<h2><a name="syntax">Syntax of Lambda Expressions</a></h2>
<p>A lambda expression consists of the following:</p>
<ul>
<li><p>A
comma-separated list of formal parameters enclosed in
parentheses. The <code>CheckPerson.test</code> method contains one parameter,
<code>p</code>, which represents an instance of the
<code>Person</code> class.</p>
<p><b>Note</b>: You can
omit the data type of the parameters in a lambda expression. In
addition, you can omit the parentheses if there is only one
parameter. For example, the following lambda expression is also
valid:</p>
<pre class="codeblock">p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25</pre></li>
<li><p>The arrow token, <code>-></code></p></li>
<li><p>A
body, which consists of a single expression or a statement block. This example uses the following expression:</p>
<pre class="codeblock">p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25</pre>
<p>If you
specify a single expression, then the Java runtime evaluates the
expression and then returns its value. Alternatively, you can use
a return statement:</p>
<pre class="codeblock">p -> {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}</pre>
<p>A return statement is not an expression; in a lambda expression,
you must enclose statements in braces (<code>{}</code>). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:</p>
<pre class="codeblock">email -> System.out.println(email)</pre>
</li>
</ul>
<p>Note that a lambda expression looks a lot like a method
declaration; you can consider lambda expressions as anonymous
methods—methods without a name.</p>