Java8 lambda expression (1)-Basic syntax

Source: Internet
Author: User

Reference: http://www.cnblogs.com/andywithu/p/7344507.html

A lambda expression, an expression with arguments, looks at the following example for a clearer understanding of the lambda expression: (1)
Class student{private String name;     Private Double score;        Public Student (String name, Double score) {this.name = name;    This.score = score;    } public String GetName () {return name;    } public Double Getscore () {return score;    } public void SetName (String name) {this.name = name;    } public void SetScore (Double score) {This.score = score;                } @Override Public String toString () {return "{" + "\" name\ ": \" "+ name +" \ ""    + ", \" score\ ": \" "+ score +" \ "" + "}"; }} @Testpublic void Test1 () {list<student> studentlist = new Arraylist<student> () {{Add (            New Student ("STU1", 100.0));            Add (New Student ("Stu2", 97.0));            Add (New Student ("Stu3", 96.0));        Add (New Student ("Stu4", 95.0));    }    }; Collections.sort (Studentlist, New comparator<student> () {@Override public int comPare (Student O1, Student O2) {return Double.compare (O1.getscore (), O2.getscore ());    }    }); System.out.println (studentlist);}
(1) The code calls the Collections.sort method to sort the collection, where the second parameter is a class, exactly an anonymous inner class, and the sort method invokes the Compare method in the inner class to position the list, because the type of the parameter in Java can only be a class or a basic data type, so though However, a comparator class is passed in, but the only thing that needs to be passed is the Compare method, which is specifically for an interface with only one method (that is, a functional interface), and comparator is a functional interface
@FunctionalInterfacepublic interface comparator<t> {    int compare (t O1, T O2);}
The function of @FunctionalInterface is to identify an interface as a functional interface, at which point there can only be an abstract method in comparator. The code in (1) after using the lambda expression is modified as follows (2)
public void test1_ () {        list<student> studentlist = new arraylist<student> () {            {                Add (new Student ("STU1", 100.0));                Add (New Student ("Stu2", 97.0));                Add (New Student ("Stu3", 96.0));                Add (New Student ("Stu4", 95.0));            }        ;        Collections.sort (Studentlist, (S1,S2), Double.compare (S1.getscore (), S2.getscore ()));        System.out.println (studentlist);    }
For cases with multiple parameters, syntax: 1.     The basic format of the AMBDA expression is (x1,x2)->{expression ...}; 2. In the above formula, the lambda expression has two parameters, so the parentheses on both sides cannot be omitted, and the parameter type can omit 3. If the expression has only one row, then the curly braces on either side of the expression can be omitted another common example is to create a new thread without using a lambda expression (3)
public void Testthread () {        new Thread (new Runnable () {            @Override public            void Run () {                System.out.println ("Hello, I am thread!");            }        ). Start ();    }
Where the Runnable interface is also a functional interface, the source code is as follows
@FunctionalInterfacepublic interface Runnable {    /**     * When an object implementing interface <code> Runnable</code> is used     * To create a thread, starting the thread causes the object ' s     * <code>run< ;/code> method to being called in that separately executing     * thread.     * <p> * The general contract of the method <code>run</code> are that it could * take any     action W Hatsoever.     *     * @see     java.lang.thread#run () */public    abstract void run ();
Convert it to a lambda expression as (4)
public void Testthread_ () {    new Thread ((), System.out.println ("Hello, I Am thread!")). Start ();}
For cases with no parameters, the syntax: 1. The parentheses of the argument cannot be omitted, and if there is only one expression, you can omit the curly brace and the semicolon at the end of the statement we construct a functional interface with only one argument
@FunctionalInterfacepublic interface Myfunctionalinterface {public    void single (String msg);}/** * requires individual parameters */public s tatic void Testonepar (Myfunctionalinterface myfunctionalinterface) {    myfunctionalinterface.single ("msg");}/**     * One parameter can omit the parentheses of the argument     */    @Test public    void Testoneparameter () {        Testonepar (x-> SYSTEM.OUT.PRINTLN (x));    }
For cases with only one argument, syntax: 1. The parentheses of the arguments can be omitted here we have created a functional interface in order to demonstrate that there is only one parameter, in fact Java8 has provided us with a lot of common function interface common functions: Provide any kind of parameters, Returns a return value of any other type. R apply (t T); Consumer: Provides an argument of any type that returns a null value. void Accept (T t); Supplier: The parameter is null to get the return value of any one type. T get (); Predicate: Provides any type of parameter that returns a Boolean return value. Boolean test (t); Therefore, for the above case, we can use the consumer class directly,
/**     * requires a single parameter *    /public static void TestOnePar1 (Consumer unaryoperator) {        unaryoperator.accept ("MSG") ;    }

Java8 lambda expression (1)-Basic syntax

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.