Java 8 lambda-chapter II-LAMBDA expression __java

Source: Internet
Author: User
Tags event listener
Chapter II: lambda expression
The biggest change in Java8 is the introduction of lambda expressions, a compact way of passing behavior, which is what's left of the book, so let's go into it.


Write the first lambda expression
Swing is a platform-independent GUI library in which there are many common habits, such as registering an event listener to know what the user clicked on, and this event listener can perform some action to respond to user input.
Button.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent event) {
System.out.println ("button clicked");
}
})
In this example, we created an object that implements the ActionListener interface, which has only one method actionperformed (), which is invoked when the user clicks the button, and the anonymous inner class provides the implementation of the method.


Anonymous internal classes are designed to allow Java programmers to pass behavior and pass data as easily, unfortunately, they are not easy, in order to invoke the code processing logic still has four lines of template code, duplicate template code is not the only problem, this code is difficult to read, we do not want to pass an object, And just need to pass some kind of behavior, in JAVA8 we can write more concise
Button.addactionlistener (Event-> System.out.println ("button cliecked"));


Unlike passing an object that implements an interface, we pass a code that does not have a named function, the event is a parameter, like the parameters of an anonymous inner class,-> separates the arguments from the contents of the lambda expression. Another difference with anonymous internal classes is that we affirm the variable's way, before we need to display the declaration type ActionEvent, in which case we do not need to provide the type, the compilation can pass, and what happens behind this is that Javac gets the event type from the context, This is obtained from the addActionListener signature, which means that you do not need to display a declaration of its type, and we will discuss the design in more detail, and first let's look at several different ways of writing lambda expressions.


How to use lambda expressions in the right places.
Here are a few examples of using lambda expressions
①runnable noarguments = ()-> System.out.println ("Hello World");
②actionlistener oneargument = event-> System.out.println ("button click");
③runnable multistatement = ()->{
System.out.print ("Hello");
SYSTEM.OUT.PRINTLN ("World");
}
④binaryoperator<long> add = (x, y)-> x + y;
⑤binaryoperator<long> addexplicit = (long x, long y)-> x + y;


① shows how to use a lambda without parameters, using a pair of empty parentheses to indicate no arguments, an expression that implements a runnable lambda, which has only one method run () that does not accept any arguments and returns void.
② shows the expression of a lambda with only one argument.
Unlike a Lambda,③ that contains only one expression, it contains a block of code that is contained in a curly brace, which is similar to the usual method and can return results or throw an exception before it ends.
④ contains multiple parameters, in which case it is necessary to consider how to read this expression, this line of code does not add two numbers, it creates a function to add two numbers, add this variable is not two number of sum, but a sum of two number of functions.
⑤ so far, all lambda expression parameter types are determined by the compiler, which is great, but there are times when we need to be explicit about the parameter type.


All of the above expressions indicate that a lambda expression relies on the context, and is judged by the compiler, which is not entirely new, that the initialization of the array in example2-4 relies on the context, and null, and only when it is allocated does it know its type.
Final string[] array = {"Hello", "World"};




Using Values
When you used to use anonymous inner classes, you might encounter situations where you want to use an external variable in an inner class, you need to declare an external variable to be final, and a variable declared final means you cannot point the variable to another object.
Final String name = GetUserName ();
Button.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent event) {
SYSTEM.OUT.PRINTLN ("HI" +name);
}
})
In Java8, this restriction is relaxed and can refer to a non final parameter, although it is not declared final, but must be treated as a final type and cannot change the object it refers to, otherwise it will be an error.
String name = GetUserName ();
Button.addactionlistener (Event-> System.out.println ("HI" + name));
If you assign a value to a variable multiple times, and you count it as a reference in a lambda expression, you get a mutation error.
String name = GetUserName ();
Name = Formatusername (name);
Button.addactionlistener (Event-> System.out.println ("HI" + name));
That's why people think of lambda expressions as closures, and there's a lot of debate in the programming language about whether or not Java has closures because it only references final variables, and in order to avoid this unwarranted controversy, I call them lambda expressions in this book. But no matter what I call them, I've already mentioned that lambda expressions are statically typed, so let's look at the expressions themselves: they call them functional interfaces.




Function-Type interface
A functional interface is an interface that has only one abstract method, and is used as a type of lambda expression.
In Java, all parameters have types, and if we pass in 3 to a method, which is the int type, what is the type of lambda?


Type discussion.
In some cases, you need to provide an exact type flag, and my advice is how easy it is for you and your team to read how to do it. There are times when you don't label the type to make it look more concise, and sometimes you add a type flag to make it more obvious. I've found that at first it might seem useful to add a type, but then maybe you'll just add it when necessary, and this chapter will provide you with a few principles that make it easy to tell if it's necessary to add.
The type of discussion is actually a continuation of the type discussion in Java7.
map<string, integer> oldwordcount = new hashmap<string, integer> ();
map<string, integer> diamonwordcounts = new hashmap<> ();
For variable Oldwordcount We explicitly specify the type of the generic, but diamonwordcounts uses diamond operator, the generic type does not indicate that the compiler specifies its type.
If you pass a constructor directly to a method, the compiler can also point to the generic type, and the same java7 allows the generic type of the constructor to be vacated, java8 allow the parameter type of the lambda expression.
In fact, there is no magic, the Java compiler looks for the type of the parameter determination in the context of a lambda expression.
Let's discuss it in more detail with a few examples.
In the following two cases, we pass in a parameter to a function interface, so it is easy to determine the difference between the two.
First example:
predicate<integer> ATLEAST5 = x-> x >5
Unlike the previous ActionListener example, predicate is a lambda expression with a return value, where the expression is x > 5, and the value of the expression is the return value of the lambda expression.
We can see that predicate has a generic parameter, in the last expression we pass in an int value, the Java compiler detects whether the return value is a Boolean value.
public interface predicate<t>{
Boolean test (T);
}


Let's take a look at another, more complicated example:
Binaryoperator interface
Binaryoperator<long> addlongs = (x, y)-> x+y;
This interface has two parameters and a return value, two parameter types are the same, in the instance we use the type long, but if not enough information the compiler will return a mutation error, for example, in the following expression will throw a mutation error
Binaryoperator add = (x, y)-> x + y;




Summarize:
The 1.LAMBDA expression is not named and is used to pass the operation as data.
2. The function interface refers to an interface that has only one abstract method, and is treated as a type of lambda expression.

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.