New features of Java JDK1.8 __java

Source: Internet
Author: User

The meaning of a lambda

Lambda represents the mathematical symbol "λ", in the domain of the computer, λ represents the "lambda calculus", which expresses the most basic concept in the computer: "Call" and "permutation". In many dynamic languages and C # there is a corresponding lambda syntax, which is designed to simplify the code and improve operational efficiency.


second, the background of the Lambda project , refer to here.

Whether object-oriented language or functional language, basic values can be dynamically encapsulated into the program action: object-oriented language through the "method", functional language through the function.

There are many different definitions of "methods" and "functions", supplemented by an explanation of the IBM Knowledge Base:

In an object-oriented language, a method is not a first-order value (first-class value), and in a functional language, a function is a first-order value. In a functional language, a function can act as a return value or parameter of another function, or as a value of a variable, a function can nest a definition, whereas a "method" in an object-oriented language does not.

Java can be said to be an object-oriented language representative, if you want to call its methods, you need to create the object first. However, Java objects are "heavyweight", and the instantiation of the object of a specific class requires a two-stage definition and declaration. For example, define a method and assign an initial value to an internal field. But there are many situations where an object contains only one method, such as a class that implements the "Callback interface" feature in the API, which has an interface in swing:


Java code <span><span><span style= "" >public interface ActionListener {void actionperformed (Action   Event e); }</span></span></span>


Most of the existing implementations are:


Java code <span><span><span style= "" >button.addactionlistener (new ActionListener () {public void act     Ionperformed (ActionEvent e) {ui.dazzle (E.getmodifiers ()); });</span></span></span>


Many of the existing class libraries are based on this design implementation, so anonymous inner classes are especially important for code that is explicitly defined to run on a separate thread. These anonymous inner classes exist only in the thread that created it. But in the field of parallel computing, CPU manufacturers are focused on developing multi-core technology to boost CPU functionality, which can hardly rely on multi-core to improve performance.



Since callback functions are more closely related to other functional syntaxes, it is necessary to establish as lightweight a data model as possible (from the coding perspective, the performance aspect is described below). For this, the disadvantages of anonymous internal classes are as follows:

1. The grammar is relatively complex.

2. In the context of invoking the inner class, the guide and the reference to this are easily confused.

3. Class loading and instance creation syntax are unavoidable.

4. You cannot refer to external non-final objects.

5. Cannot abstract control flow



To address these issues, the lambda project is dedicated to

1. Eliminate issues 1 and 2 by introducing simpler expressions and definition rules for local variables.

2. Avoid question 3, and define a more flexible and friendly syntax. This is simply evasive, and class loading and instantiation are inherently unavoidable. The following will explain.

3. Improve problem 4, allowing users to use the final valid local variables.


However, the Lambda project currently does not solve all problems with internal classes. Questions 4 and 5 are not fully resolved, and this plan continues to improve in the class version. In terms of performance, the original text did not mention it, but some added later.



iii. Lambda Usage

As you can see from the above, the lambda syntax is an improvement on the callback interface and anonymous inner class, so the lambda syntax is currently only for partial interfaces, which are characterized by an abstract method, which is called the Sam type in the Lambda project early (Sam = Single Abstract method is a single abstraction. In the latest document (that is, this version), they have a new name called the function interface (functional interface), such as:
1 java.lang.Runnable 2 java.util.concurrent.Callable 3 java.security.PrivilegedAction 4 Java.util.Comparator 5 Java.io.FileFilter 6 Java.nio.file.PathMatcher 7 Java.lang.reflect.InvocationHandler 8 Java.beans.PropertyChangeListener 9 Java.awt.event.ActionListener Javax.swing.event.ChangeListener
The syntax of a lambda consists of three parts 1, a parameter list 2, an arrow symbol "->" 3, and a code block.



Where the code block resembles a method body, the return statement returns control to the caller of the anonymous method (anonymous), the lambda expression, and the break and continue cannot appear at the top of the function body, but can appear inside the loop If the code block has the final result, then each control path must have a return or throw exception.

If the code block has a simple line, you can omit the return keyword and the "{}" symbol (The following example is based on the JDK 1.8 Lambda preview), such as:



Java code    <span><span><span style= "" >public class lambdatest {            public static void main (String ...  args)  {           //here are {} and return  and  ;            Runnable r =  ()  -> {  system.out.println ("Hello world"); };                       //here do not need {} and return            java.util.Comparator<String> c =  (STRING&NBSP;S1, &NBSP;STRING&NBSP;S2)  -> s2.length ()-s1.length ();                    r.run ();            syStem.out.println (C.compare ("S1",  "12323");       }  }</span ></span></span>  



The output is:

Hello World

3



In addition to these existing interfaces, we can also customize the function interface:


Java code <span><span><span style= "" >public class Lambdatest {interface Lambdainterface {       public void Me (String str); public static void Main (string ... args) {Lambdainterface Li = (string s)->{system.out.println (s);           };       Li.me ("Hello world!"); }}</span></span></span>

The output is:


Hello world!


The new lambda method is really a lot simpler in syntax. It's also a lot more elegant than the first time the lambda syntax is published.



Four, the bytecode of the lambda code block


After reading the grammar is really very simple, then how the lambda is achieved, it must be from the byte code investigation. Here, in contrast to the anonymous inner class, compile the following code:


Java code <span><span><span style= "" >public class Lambdatest

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.