Java Lambda expression usage

Source: Internet
Author: User
use of lambda expressions three components of a lambdaA comma-delimited form parameter in parentheses, which is the parameter of the method inside the function interface.
IOperation operation = (param)-> add_num + param;
An arrow symbol:->
Collections.sort (ArrayList, (S1,S2)-> s1.getage () >= s2.getage ()? -1:1);
Method body, which can be an expression and a code block
Thread thread = new Thread (()->{
            System.out.println ("Lambda parameterless:" + thread.currentthread ()); GetName ();
        });
interface definition for lambda @FunctionalInterface Annotations

A function-time expression interface supports only one abstract method.

Declare functional annotations and detect interface writing at compile time. (I use the idea compiler, do not write this note also line) interface definition in the example interface, the ToString, Hashcode, equals in the interface that support static in the Defualt method interface cannot be overloaded

Public interface IOperation {
    /**
     * addition Calculation
     * @param a
     * @return
    /int addoperation (int a);

    Default int GetCount () {return
        1;
    }

    Boolean equals (Object O);

    Static String GetVersion () {return
        ' 1.1 ';
    }
}
Java.util.function-supported lambda expressions

The Java.util.function package provides a number of function-supported objects.
Sometimes we can use this write object instead of function interface predicate t as parameter, return Boolean type, as a function interface object of complex judgment logic.

The male
        list<person> reslist = Lists.newarraylist () in the filter set
        ; for (int i =0;i<10;i++) {
            Boolean flag = i% 2 = 0;
            Reslist.add (New Lambdaclient (). New Person ("name_" +i,20+i,flag);
        }
        1. The concrete implementation logic of predicate function interface
        predicate<person> ismanpredicate = (person person)-> person.issex ();
        list<person> manlist = Lists.newarraylist ();
        Reslist.foreach (person-> {
            if (ismanpredicate.test) {
                manlist.add (person);
            }
        });

        System.out.println ("male is" + manlist);
Function
2. Function
        Function<integer, string> F2 = (t)->string.valueof (t);
        String s = f2.apply (2);
        SYSTEM.OUT.PRINTLN ("Function apply result" + s);
Consumer T as a parameter and does not return a result.
3. Consumer
        consumer<person> personconsumer = (person p)-> {
            System.out.println (' My name is ' + p.getname ( + ' age is ' + p.getage ()
                    + ' sex is ' + (P.issex ()?) Male ":" female "));
        Personconsumer.accept (Reslist.get (4));
Stream (Stream) operation of the collection the Set Confluence calculation method is divided into serial flow (sequential) and parallel flow (parallel)
public static list<integer> Getintegerlist () {list<integer> List = lists.newarraylist ();
            for (int i=1;i<=10000000;i++) {Integer count = new Random (). Nextint (i);
        List.add (count);
    } return list; }/** * Serial stream/public static void Sequentialstreamdemo () {list<integer> List = Getintegerl
        IST ();
        Serial ordering, and calculating time long start = System.nanotime ();
        Long Count = ((Stream) List.stream (). Sequential ()). Sorted (). Count ();
        Long end = System.nanotime ();
        Long usetime = TimeUnit.NANOSECONDS.toMillis (End-start);
    System.out.println ("Sequential sort count:use Time is MS" + Usetime); }/** * Parallel flow/public static void Parallelstreamdemo () {list<integer> List = Getintegerli
        St ();
        Serial ordering, and calculating time long start = System.nanotime ();
        Long Count = ((Stream) List.stream (). Parallel ()). Sorted (). Count (); Long End = System.nanotime ();
        Long usetime = TimeUnit.NANOSECONDS.toMillis (End-start);
    System.out.println ("Parallell sort count:use Time is MS" + Usetime); }
the process of set confluence calculation is divided into intermediate operation and termination operation .An intermediate operation returns an object or stream, such as Filter,sorted,map,group

Returns a non-stream object, such as foreach (), sum (), ToArray (), and so on

public static void Streamlistdemo () {
    list<lambdaclient.person> personlist = Lists.newarraylist ();
    for (int i=0;i<50;i++) {
        personlist.add (new Lambdaclient.person ("Name_" +i,15+i));
    }
    Filter for persons over 30 years old
    /**
     * Filter incoming parameters are predicate<t> function.
     * foreachordered incoming parameter is consumer<t> function type *
     *
    personlist.stream (). Filter (Person-> person.getage () >30). foreachordered (Person
            -> System.out.println ("Person of age 30+" + person)
    ;

}

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.