Follow the Java 8– to learn about lambda

Source: Internet
Author: User


Source: Cavalier Nice


Lambda is one of the most important features since the advent of JAVA8, which allows us to complete a function with simple and smooth code. For a long time, Java was a language of redundancy and lack of functional programming capability, and this style of programming was introduced with the popular java8 of functional programming. Before that we were all writing anonymous internal classes to do these things, but sometimes this is not a good practice, this article will introduce and use lambda, with you to experience the magic of functional programming.





What is a lambda?


A lambda expression is a piece of code that can be passed, and its core idea is to transform the passed data in object-oriented into transitive behavior. Let's review what we're going to do before we use JAVA8, which is what we did before we wrote a thread:


< Code class= "Java plain" >runnable r =newrunnable ( {&NBSP;&NBSP;&NBSP;&NBSP;@OverrideCode class= "Java Spaces" >&NBSP;&NBSP;&NBSP;&NBSP;publicvoidrun () {         system.out.println (" Do something. ";          }}


Some people will write a class to implement the Runnable interface, so there is no problem, we notice that there is only one run method in this interface, when the Runnable object to the thread object as a construction parameter when creating a thread, run will output do something. We implemented this method by using an anonymous inner class.


This is actually a code-as-data example, in the Run method is a thread to perform a task, but the above code in the task content has been specified dead. When we have a number of different tasks, we need to write the above code repeatedly.


The purpose of designing anonymous inner classes is to make it easier for Java programmers to pass code as data. However, anonymous internal classes are not simple enough. In order to execute a simple task logic, we have to add 6 lines of cumbersome boilerplate code. So what if it's a lambda?



Runnable r = () -> System.out.println("do something.");


Well, the code looks cool, and you can see that we've done it with () and, it's a function without a name, and no one and no parameters, so simple. Separating the parameters from the implementation logic using the, when running this thread, executes the code snippet that follows, and the compiler helps us with the type deduction, which can be a piece of logic contained in {}. Let's take a look at the syntax of Lambda.


Basic syntax


In Lambda we follow the following expressions to write:



expression = (variable) -> action
    • Variable: This is a variable, a placeholder. Like X, Y, Z, can be multiple variables;
    • Action: Here I call it action, which is the logical part of the code we implement, which can be a line of code or a snippet of code.


You can see the format of lambda expressions in Java: parameters, arrows, and action implementations, and when an action implementation cannot be done with one line of code, you can write a piece of code wrapped with {}.



A lambda expression can contain multiple parameters, such as:



intsum = (x, y) -> x + y;


This time we should think that this code is not the sum of the previous x and Y numbers, but instead creates a function to calculate the sum of two operands. The following is received with the int type, and the return is omitted for us in lambda.


Function-Type interface


A functional interface is an interface that has only one method, and is used as the type of a lambda expression. The previous example is a functional interface, look at the JDK runnable source code


@FunctionalInterfacepublicinterfaceRunnable {    /**     * 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 be called in that separately executing     * thread.     * <p>     * The general contract of the method <code>run</code> is that it may     * take any action whatsoever.     *     * @see     java.lang.Thread#run()     */    publicabstractvoidrun();}


There is only one abstract method run, in fact you do not write public abstract is also possible, the method defined in the interface is public abstract. Also use annotation @functionalinterface to tell the compiler that this is a functional interface, of course, you do not write this can also, after the identification of the function only an abstract method, when you try to write multiple methods in the interface, the compiler will not allow this to do.


Try a functional interface


Let's write a functional interface and enter an age to determine if the person is an adult.


publicclassFunctionInterfaceDemo {@FunctionalInterface interfacePredicate <T> {booleantest (T t);} / ** * Perform Predicate judgment * * @param age age * @param predicate Predicate functional interface * @return returns a Boolean result * / publicstaticbooleandoPredicate (intage, Predicate <Integer> predicate) {returnpredicate.test (age);} publicstaticvoidmain (String [] args) {booleanisAdult = doPredicate (20, x-> x> = 18); System.out.println (isAdult);}}


From this example we can easily complete whether it is an adult action, followed by the determination of whether it is an adult, before our practice is generally written to determine whether it is an adult method, is not able to share the judgment. And in this case, the only thing you have to do is pass in the behavior (judging whether it's an adult, or whether it's more than 30 years old), and the functional interface tells you what the result is.



In fact, such as the interface in the above example, the Great JDK designer prepared the Java.util.function package for us.






The predicate function interface we wrote earlier is also an implementation of the JDK species, which are broadly divided into the following categories:





Consumer Interface Example
publicstaticvoiddonation (Integer money, Consumer<integer> Consumer) {&NBSP;&NBSP;&NBSP;&NBSP;consumer.accept (money); }Publicstaticvoidmain (string[] args) {&NBSP;&NBSP;&NBSP;&NBSP;Code class= "Java Plain" >donation (1000, money- System.out.println ("good melody donated to Blade"+money+"meta"


Example of a supply-only interface


publicstaticList<Integer> supply(Integer num, Supplier<Integer> supplier){       List<Integer> resultList =newArrayList<Integer>()   ;       for(intx=0;x<num;x++)            resultList.add(supplier.get());       returnresultList ;}publicstaticvoidmain(String[] args) {    List<Integer> list = supply(10,() -> (int)(Math.random()*100));    list.forEach(System.out::println);}


Example of a function-type interface


Convert String to Integer


publicstaticInteger convert(String str, Function<String, Integer> function) {    returnfunction.apply(str);}publicstaticvoidmain(String[] args) {    Integer value = convert("28", x -> Integer.parseInt(x));}
Assertion-Type Interface example


Filter out only 2 characters of fruit



publicstaticList <String> filter (List <String> fruit, Predicate <String> predicate) {List <String> f = newArrayList <> (); for (String s: fruit) {if (predicate.test (s)) {f .add (s);}} returnf;} publicstaticvoidmain (String [] args) {List <String> fruit = Arrays.asList ("banana", "cantaloupe", "durian", "pitaya", "juicy peach" ); List <String> newFruit = filter (fruit, (f)-> f.length () == 2); System.out.println (newFruit);}
Default method


In the Java language, a method defined in one port must be implemented by an implementation class. But when a new API is added to the interface, the implementation class modifies the implementation as agreed, and the Java8 API adds a number of methods to the existing interface, such as the sort method added to the list interface. If you follow the previous practice, then all the implementation classes have to implement the Sort method, the JDK writers must be very mad.



Fortunately, we used the Java8, and this problem will be well resolved, introducing a new mechanism in the JAVA8, which supports declaring the method in the interface while providing the implementation. This is exciting, you have two ways to complete 1. Declares a static method within an interface 2. Specifies a default method.



Let's take a look at how the above list interface Add method in JDK8 is resolved


defaultvoidsort(Comparator<?superE> c) {    Object[] a =this.toArray();    Arrays.sort(a, (Comparator) c);    ListIterator<E> i =this.listIterator();    for(Object e : a) {        i.next();        i.set((E) e);    }}


Flip through the list interface's source code, which adds a default method of the defaults void sort (comparator<? super E> C). Add the default keyword before the return value, and with this method we can call the sort method directly.



List<Integer> list = Arrays.asList(2,7,3,1,8,6,4);list.sort(Comparator.naturalOrder());System.out.println(list);


Comparator.naturalorder () is an implementation of a natural sort, where you can customize the sorting scheme. You often see the reason that you can directly forEach using the JAVA8 operation set is also a new default method in the Iterable interface: ForEach, which is similar to the For loop, but allows the user to use a lambda expression as the body of the loop.


Original address: http://biezhi.me/2017/07/17/keep-up-with-java8-lambda.html


Follow the Java 8– to learn about lambda


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.