lambda expressions (the java™ tutorials _ learning the java language _ classes and objects)

Download Lambda Expressions (The Java™ Tutorials _ Learning the Java Language _ Classes and Objects)

Post on 06-Mar-2016

8 views

Category:

Documents

0 download

Embed Size (px)

DESCRIPTION

Lamda Has been introduced to Java 8 Version. Here is an overview

TRANSCRIPT

  • 5/3/2015 LambdaExpressions(TheJavaTutorials>LearningtheJavaLanguage>ClassesandObjects)

    https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach1 1/10

    Trail:LearningtheJavaLanguageLesson:ClassesandObjectsSection:NestedClasses

    LambdaExpressions

    Oneissuewithanonymousclassesisthatiftheimplementationofyouranonymousclassisverysimple,suchasaninterfacethatcontainsonlyonemethod,thenthesyntaxofanonymousclassesmayseemunwieldyandunclear.Inthesecases,you'reusuallytryingtopassfunctionalityasanargumenttoanothermethod,suchaswhatactionshouldbetakenwhensomeoneclicksabutton.Lambdaexpressionsenableyoutodothis,totreatfunctionalityasmethodargument,orcodeasdata.

    Theprevioussection,AnonymousClasses,showsyouhowtoimplementabaseclasswithoutgivingitaname.Althoughthisisoftenmoreconcisethananamedclass,forclasseswithonlyonemethod,evenananonymousclassseemsabitexcessiveandcumbersome.Lambdaexpressionsletyouexpressinstancesofsinglemethodclassesmorecompactly.

    Thissectioncoversthefollowingtopics:

    IdealUseCaseforLambdaExpressionsApproach1:CreateMethodsThatSearchforMembersThatMatchOneCharacteristicApproach2:CreateMoreGeneralizedSearchMethodsApproach3:SpecifySearchCriteriaCodeinaLocalClassApproach4:SpecifySearchCriteriaCodeinanAnonymousClassApproach5:SpecifySearchCriteriaCodewithaLambdaExpressionApproach6:UseStandardFunctionalInterfaceswithLambdaExpressionsApproach7:UseLambdaExpressionsThroughoutYourApplicationApproach8:UseGenericsMoreExtensivelyApproach9:UseAggregateOperationsThatAcceptLambdaExpressionsasParameters

    LambdaExpressionsinGUIApplicationsSyntaxofLambdaExpressionsAccessingLocalVariablesoftheEnclosingScopeTargetTyping

    TargetTypesandMethodArgumentsSerialization

    IdealUseCaseforLambdaExpressions

    Supposethatyouarecreatingasocialnetworkingapplication.Youwanttocreateafeaturethatenablesanadministratortoperformanykindofaction,suchassendingamessage,onmembersofthesocialnetworkingapplicationthatsatisfycertaincriteria.Thefollowingtabledescribesthisusecaseindetail:

    Field Description

    Name Performactiononselectedmembers

    PrimaryActor Administrator

    Preconditions Administratorisloggedintothesystem.

    Postconditions Actionisperformedonlyonmembersthatfitthespecifiedcriteria.

    MainSuccessScenario

    1. Administratorspecifiescriteriaofmembersonwhichtoperformacertainaction.2. Administratorspecifiesanactiontoperformonthoseselectedmembers.3. AdministratorselectstheSubmitbutton.4. Thesystemfindsallmembersthatmatchthespecifiedcriteria.5. Thesystemperformsthespecifiedactiononallmatchingmembers.

    Extensions 1a.AdministratorhasanoptiontopreviewthosememberswhomatchthespecifiedcriteriabeforeheorshespecifiestheactiontobeperformedorbeforeselectingtheSubmitbutton.

    FrequencyofOccurrence

    Manytimesduringtheday.

    SupposethatmembersofthissocialnetworkingapplicationarerepresentedbythefollowingPersonclass:

    Documentation

    TheJavaTutorials

  • 5/3/2015 LambdaExpressions(TheJavaTutorials>LearningtheJavaLanguage>ClassesandObjects)

    https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach1 2/10

    publicclassPerson{

    publicenumSex{

    MALE,FEMALE

    }

    Stringname

    LocalDatebirthday

    Sexgender

    StringemailAddress

    publicintgetAge(){

    //...

    }

    publicvoidprintPerson(){

    //...

    }

    }

    SupposethatthemembersofyoursocialnetworkingapplicationarestoredinaListinstance.

    Thissectionbeginswithanaiveapproachtothisusecase.Itimprovesuponthisapproachwithlocalandanonymousclasses,andthenfinisheswithanefficientandconciseapproachusinglambdaexpressions.FindthecodeexcerptsdescribedinthissectionintheexampleRosterTest.

    Approach1:CreateMethodsThatSearchforMembersThatMatchOneCharacteristic

    Onesimplisticapproachistocreateseveralmethodseachmethodsearchesformembersthatmatchonecharacteristic,suchasgenderorage.Thefollowingmethodprintsmembersthatareolderthanaspecifiedage:

    publicstaticvoidprintPersonsOlderThan(Listroster,intage){

    for(Personp:roster){

    if(p.getAge()>=age){

    p.printPerson()

    }

    }

    }

    Note:AListisanorderedCollection.Acollectionisanobjectthatgroupsmultipleelementsintoasingleunit.Collectionsareusedtostore,retrieve,manipulate,andcommunicateaggregatedata.Formoreinformationaboutcollections,seetheCollectionstrail.

    Thisapproachcanpotentiallymakeyourapplicationbrittle,whichisthelikelihoodofanapplicationnotworkingbecauseoftheintroductionofupdates(suchasnewerdatatypes).SupposethatyouupgradeyourapplicationandchangethestructureofthePersonclasssuchthatitcontainsdifferentmembervariablesperhapstheclassrecordsandmeasuresageswithadifferentdatatypeoralgorithm.YouwouldhavetorewritealotofyourAPItoaccommodatethischange.Inaddition,thisapproachisunnecessarilyrestrictivewhatifyouwantedtoprintmembersyoungerthanacertainage,forexample?

    Approach2:CreateMoreGeneralizedSearchMethods

    ThefollowingmethodismoregenericthanprintPersonsOlderThanitprintsmemberswithinaspecifiedrangeofages:

    publicstaticvoidprintPersonsWithinAgeRange(

    Listroster,intlow,inthigh){

    for(Personp:roster){

    if(low

  • 5/3/2015 LambdaExpressions(TheJavaTutorials>LearningtheJavaLanguage>ClassesandObjects)

    https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach1 3/10

    }

    }

    ThismethodcheckseachPersoninstancecontainedintheListparameterrosterwhetheritsatisfiesthesearchcriteriaspecifiedintheCheckPersonparametertesterbyinvokingthemethodtester.test.Ifthemethodtester.testreturnsatruevalue,thenthemethodprintPersonsisinvokedonthePersoninstance.

    Tospecifythesearchcriteria,youimplementtheCheckPersoninterface:

    interfaceCheckPerson{

    booleantest(Personp)

    }

    ThefollowingclassimplementstheCheckPersoninterfacebyspecifyinganimplementationforthemethodtest.ThismethodfiltersmembersthatareeligibleforSelectiveServiceintheUnitedStates:itreturnsatruevalueifitsPersonparameterismaleandbetweentheagesof18and25:

    classCheckPersonEligibleForSelectiveServiceimplementsCheckPerson{

    publicbooleantest(Personp){

    returnp.gender==Person.Sex.MALE&&

    p.getAge()>=18&&

    p.getAge()p.getGender()==Person.Sex.MALE

    &&p.getAge()>=18

    &&p.getAge()

  • 5/3/2015 LambdaExpressions(TheJavaTutorials>LearningtheJavaLanguage>ClassesandObjects)

    https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach1 4/10

    booleantest(Personp)

    }

    Thisisaverysimpleinterface.It'safunctionalinterfacebecauseitcontainsonlyoneabstractmethod.Thismethodtakesoneparameterandreturnsabooleanvalue.Themethodissosimplethatitmightnotbeworthittodefineoneinyourapplication.Consequently,theJDKdefinesseveralstandardfunctionalinterfaces,whichyoucanfindinthepackagejava.util.function.

    Forexample,youcanusethePredicateinterfaceinplaceofCheckPerson.Thisinterfacecontainsthemethodbooleantest(Tt):

    interfacePredicate{

    booleantest(Tt)

    }

    TheinterfacePredicateisanexampleofagenericinterface.(Formoreinformationaboutgenerics,seetheGenerics(Updated)lesson.)Generictypes(suchasgenericinterfaces)specifyoneormoretypeparameterswithinanglebrackets().Thisinterfacecontainsonlyonetypeparameter,T.Whenyoudeclareorinstantiateagenerictypewithactualtypearguments,youhaveaparameterizedtype.Forexample,theparameterizedtypePredicateisthefollowing:

    interfacePredicate{

    booleantest(Persont)

    }

    ThisparameterizedtypecontainsamethodthathasthesamereturntypeandparametersasCheckPerson.booleantest(Personp).Consequently,youcanusePredicateinplaceofCheckPersonasthefollowingmethoddemonstrates:

    publicstaticvoidprintPersonsWithPredicate(

    Listroster,Predicatetester){

    for(Personp:roster){

    if(tester.test(p)){

    p.printPerson()

    }

    }

    }

    Asaresult,thefollowingmethodinvocationisthesameaswhenyouinvokedprintPersonsinApproach3:SpecifySearchCriteriaCodeinaLocalClasstoobtainmemberswhoareeligibleforSelectiveService:

    printPersonsWithPredicate(

    roster,

    p>p.getGender()==Person.Sex.MALE

    &&p.getAge()>=18

    &&p.getAge()

  • 5/3/2015 LambdaExpressions(TheJavaTutorials>LearningtheJavaLanguage>ClassesandObjects)

    https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach1 5/10

    if(tester.test(p)){

    block.accept(p)

    }

    }

    }

    Asaresult,thefollowingmethodinvocationisthesameaswhenyouinvokedprintPersonsinApproach3:SpecifySearchCriteriaCodeinaLocalClasstoobtainmemberswhoareeligibleforSelectiveService.Thelambdaexpressionusedtoprintmembersishighlighted:

    processPersons(

    roster,

    p>p.getGender()==Person.Sex.MALE

    &&p.getAge()>=18

    &&p.getAge()p.printPerson()

    )

    Whatifyouwanttodomorewithyourmembers'profilesthanprintingthemout.Supposethatyouwanttovalidatethemembers'profilesorretrievetheircontactinformation?Inthiscase,youneedafunctionalinterfacethatcontainsanabstractmethodthatreturnsavalue.TheFunctioninterfacecontainsthemethodRapply(Tt).Thefollowingmethodretrievesthedataspecifiedbytheparametermapper,andthenperformsanactiononitspecifiedbytheparameterblock:

    publicstaticvoidprocessPersonsWithFunction(

    Listroster,

    Predicatetester,

    Functionmapper,

    Consumerblock){

    for(Personp:roster){

    if(tester.test(p)){

    Stringdata=mapper.apply(p)

    block.accept(data)

    }

    }

    }

    ThefollowingmethodretrievestheemailaddressfromeachmembercontainedinrosterwhoiseligibleforSelectiveServiceandthenprintsit:

    processPersonsWithFunction(

    roster,

    p>p.getGender()==Person.Sex.MALE

    &&p.getAge()>=18

    &&p.getAge()p.getEmailAddress(),

    email>Syste