Java: Lambda Expressions - mis see on?
Ainult ühe abstraktse meetodiga liidese rakendamine on tavaliselt suhteliselt segane. Lambda-väljendid pakuvad abinõu. Kuidas saate neid kasutada.
Java: Lambda ekspressioonid
Näiteks kaaluge järgmist funktsionaalset liidest: » liidese test {void test method (String x); } «.
- Abstraktse meetodi klassikalisel viisil rakendamise asemel võite ka aega kokku hoida ja kasutada lambda-väljendeid.
- Selleks rakendage kõigepealt liides, seejärel sisestage abstraktse meetodi parameetrid ja lõpuks meetodi tegelik deklaratsioon: » Test test = (string x) -> System.out.println (x); ". Selle jaoks võeti hiljuti kasutusele operaator » -> «.
- Kui meetodil pole parameetreid, jätke sulud lihtsalt tühjaks. Mitu parameetrit eraldatakse komadega nagu tavaliselt.
- Kui funktsioon peaks täitma mitu käsku, piiritlege Lamda funktsiooni keha lokkisulgudega : » Test test = (string x) -> {if (x.length ()> 0) {System.out.println (x) ; } else {System.out.println ("tähemärki pole"); }}; ".
- Lambda-avaldised on eriti praktilised iteratsioonide korral, kasutades ArrayListe. Kui " list " on ArrayList, võite kasutada näiteks " liste.forEach ((x) -> System.out.println (x)); «Väljutage kõik loendi elemendid.
- Abstraktse meetodi tagastamisväärtuse määramiseks võite kasutada ka Lambda avaldisi. Vaatleme liidest » liides arvuta {int arvuta (int a, int b); } «. Käsuga » lisage aritmeetika = (int a, int b) -> a + b; Näiteks rakendatakse kahe numbri liitmise meetod.