Java notes: Anonymous methods

Source: Internet
Author: User
Tags instance method

First, the basic knowledge

A lambda expression is essentially an anonymous method that is not executed independently, but is used to implement a method defined by a functional interface that contains only an interface to an abstract method.

A parameter-free lambda expression.

class Solution {    interface  mynumber {        double  getValue ();    }      Public Static void Main (string[] args) {        = ();        System.out.println (Number.getvalue ());}    }
View Code

A lambda expression with a parameter.

class Solution {    interface  mynumber {        boolean isfactor (intint  b);    }      Public Static void Main (string[] args) {        = (A, b), a% b = = 0;        System.out.println (Number.isfactor (5));}    }
View Code

Block lambda expression.

classSolution {InterfaceMyNumber {DoubleGETAVR (Double... arr); }     Public Static voidMain (string[] args) {mynumber number= (arr) {            Doubleres = 0;  for(DoubleI:arr) Res+=i; Res/=arr.length; returnRes;        }; Doubleres = NUMBER.GETAVR (1.0, 2.0, 3.0, 4.0, 5.0);    System.out.println (RES); }}
View Code


Second, generic function-type interface

classSolution {InterfaceMynumber<textendsNumber>{t Getavr (t ... arr); }     Public Static voidMain (string[] args) {MyNumber<Double> number = (arr), {            Doubleres = 0;  for(DoubleI:arr) Res+=i; Res/=arr.length; returnRes;        }; Doubleres = NUMBER.GETAVR (1.0, 2.0, 3.0, 4.0, 5.0);    System.out.println (RES); }}
View Code


Third, parameter transfer

You can pass a lambda expression as a parameter to a method, in order to pass a lambda expression as a parameter, the type of the receiving lambda expression must be the type of a functional interface that is compatible with the lambda expression.

classSolution {InterfaceMyString {string reverse (string s); }    Staticstring stroperate (MyString SF, string s) {returnSf.reverse (s); }     Public Static voidMain (string[] args) {String str= "Hello World"; MyString SF= (s){StringBuilder Builder=NewStringBuilder (s); returnbuilder.reverse (). toString ();        };    System.out.println (Stroperate (SF, str)); }}
View Code


Iv. anomalies

Lambda expressions support throwing exceptions, but if you throw a checked exception, you must be compatible with the exception listed in the abstract method throws statement of the functional interface.

classSolution {Static classEmptyarrayexceptionextendsException {emptyarrayexception () {Super("Empty Array"); }    }    InterfaceMyNumber {DoubleGETAVR (Double... arr)throwsemptyarrayexception; }     Public Static voidMain (string[] args) {mynumber number= (arr) {            if(Arr.length = = 0)                Throw Newemptyarrayexception (); Doubleres = 0;  for(DoubleI:arr) Res+=i; Res/=arr.length; returnRes;        }; Try {            Doubleres =Number.getavr ();        System.out.println (RES); } Catch(Emptyarrayexception exc) {System.out.println (Exc.getmessage ()); }    }}
View Code


Five, variable capture

A lambda expression can access variables defined within its outer scope, but this creates a special case, called a variable capture. In this case, the lambda expression can only use a substantially final local variable. The final local variable refers to a variable that can no longer change after the first assignment, which means that the lambda expression cannot modify a local variable in the outer scope, that is, the base type or the value of the reference type, but can invoke a method of the reference type.

Vi. Method References

A static method reference.

classSolution {InterfaceMyString {string reverse (string s); }    Staticstring StrReverse (string s) {StringBuilder builder=NewStringBuilder (s); returnbuilder.reverse (). toString (); }    Staticstring stroperate (MyString SF, string s) {returnSf.reverse (s); }     Public Static voidMain (string[] args) {String str= "Hello World"; System.out.println (Stroperate (Solution::strreverse, str));//Delivery Method Reference    }}
View Code

The instance method reference.

classSolution {InterfaceMyString {string reverse (string s); } string StrReverse (String s) {StringBuilder builder=NewStringBuilder (s); returnbuilder.reverse (). toString (); }    Staticstring stroperate (MyString SF, string s) {returnSf.reverse (s); }     Public Static voidMain (string[] args) {Solution Solution=Newsolution (); String Str= "Hello World"; System.out.println (Stroperate (Solution::strreverse, str));//Delivery Method Reference    }}
View Code

Generic method Reference.

classSolution {InterfaceMyarray<t> {        Booleancontain (t[] arr, T x); }    Static<T>BooleanArrcontain (t[] arr, T x) { for(T I:arr)if(I.equals (x))return true; return false; }    Static<T>BooleanArroperate (myarray<t>AF, t[] arr, T x) {        returnAf.contain (arr, x); }     Public Static voidMain (string[] args) {integer[] arr= {1, 2, 3, 4, 5}; System.out.println (Arroperate (solution::<integer>arrcontain, arr, 0)); }}
View Code

Constructor reference.

InterfaceMyInterface {MyClass constructor (intval);}classMyClass {Private intVal; MyClass (intval) {         This. val =Val; } MyClass () {Val= 0; }    intGetval () {returnVal; }}classSolution { Public Static voidMain (string[] args) {myinterface MF= MyClass::New;//match MyClass (int val)MyClass mc = mf.constructor (100);    System.out.println (Mc.getval ()); }}
View Code

Generic constructor Reference.

InterfaceMyinterface<t>{MyClass constructor (T val);}classMyclass<t> {    PrivateT Val; MyClass (T val) { This. val =Val; } T Getval () {returnVal; }}classSolution { Public Static voidMain (string[] args) {MyInterface<Double> MF = MyClass::New; MyClass MC= Mf.constructor (100.0);    System.out.println (Mc.getval ()); }}
View Code

Pre-defined functional interfaces

Usually we don't need to define the function interface ourselves, Java has provided some predefined functional interfaces.

Unaryoperator<t> Applies a unary operation to an object of type T and returns the result, with the method named apply.
Binaryoperator<t> Operates on two objects of type T and returns the result, with the method named apply.
Consumer<t> Applies an action to an object of type T, and the method is named accept.
Supplier<t> Returns an object of type T, with a method named get.
Function<t, r> Applies an action to an object of type T, and returns an object of type R, with the method named apply.
Predicate<t> Determines whether an object of type T satisfies a constraint, returns a Boolean value, and the method name is test.

Predefined functional interfaces Use

Import Java.util.function.BinaryOperator; class Solution {    publicstaticvoid  main (string[] args) {        binaryoperator <Integer> op = (A, b), A + B;        System.out.println (op.apply (10, 100)); //  the     }}
View Code

Java notes: Anonymous methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.