Java 8 has a simple understanding of Lambda expressions and functional interfaces.

Source: Internet
Author: User

Java 8 has a simple understanding of Lambda expressions and functional interfaces.

Java 8 is called the largest version ever changed in Java history. There are many important new features. The core is to add Lambda expressions and StreamAPI. The two can also be used together. First, let's look at what a Lambda expression is.

Using Lambda expressions not only makes the code simple, but also readable. The most important thing is that the amount of code is reduced a lot. However, to some extent, these features have been widely used in Scala and other JVM languages.

It's not surprising that the Scala community is incredible, because many Java 8 contents seem to have been moved from Scala. To some extent, the syntax of Java 8 is more detailed but not very clear than Scala, but it does not explain anything. If so, it may build Lambda expressions like Scala.

On the one hand, if Java continues to develop and implement functions already implemented by Scala around Lambda, Scala may not be needed. On the other hand, if it only provides some core functions, such as helping anonymous internal classes, Scala and other languages will continue to thrive and may outperform Java. In fact, this is the best result. Only when there is competition can we make progress. Other languages continue to develop and grow, and there is no need to worry about whether they will be outdated.

Lambda expressions. the Wikipedia interpretation is an operator used to represent anonymous functions and closures. I think this explanation is abstract. Let's look at an example.

public class SwingTest {  public static void main(String[] args) {    JFrame jFrame = new JFrame("My JFrame");    JButton jButton = new JButton("My JButton");    jButton.addActionListener(new ActionListener() {      @Override      public void actionPerformed(ActionEvent e) {                System.out.println("Button Pressed!");      }     });         jFrame.add(jButton); jFrame.pack();     jFrame.setVisible(true);     jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   }}

This is a piece of Swing programming code. It binds a listener event to the Button. When you click the Button, it outputs "ButtonPressed!" in the console! "Content. Here, an anonymous internal class instance is created to bind to the listener, which is also a common code organization in the past. But after a closer look, we will find that what we actually focus on is an ActionEvent-type parameter e and the statement System. out. println ("ButtonPressed! ");.

If you replace the code used to create an interface instance using an anonymous internal class in the previous program with a Lambda expression, the Code is as follows:

public class SwingTest {public static void main(String[] args) {  JFrame jFrame = new JFrame("My JFrame");  JButton jButton = new JButton("My JButton");  jButton.addActionListener(e -> System.out.println("Button Pressed!"));  jFrame.add(jButton);  jFrame.pack();  jFrame.setVisible(true);  jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}

Focus on the changes in the most intermediate part of the Code, from the original six lines of code, now one line can be implemented. This is a simple form of Lambda expressions.
The syntax of Lambda expressions is as follows:

(param1,param2,param3) -> {//todo}

Here, the type program of the parameter can be inferred according to the context, but not all types can be inferred. In this case, we need to declare the parameter type, parentheses can be omitted when there is only one parameter. When the todo part has only one line of code, the braces outside can be omitted. For example

In addition to the concise code, what changes does Lambda expressions bring to us?

We recall that in Java, we cannot pass functions as parameters to a method, nor declare that the return value is a function method. Before Java 8, the answer is yes.

In the above example, we can pass a piece of code logic as a parameter to the listener, telling the listener that you can do this when the event is triggered, instead of using anonymous internal classes as parameters. This is another new feature of Java 8: functional programming.

There are many languages that support functional programming. In JavaScript, It is very common to pass functions as parameters or return values as a function. JavaScript is a very common functional language.

Lambda adds the missing functional programming features to Java, so that we can treat functions as first-class citizens.

In functional programming languages, Lambda expressions are of the type of functions. In Java, Lambda expressions are objects and must be attached to a special type of object --Function interface (FunctionalInterface ).

Next, let's take a look at the definition of functional interfaces:

If an interface has only one abstract method (the methods in the Object class are not included), this interface can be seen as a functional interface.

@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 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()   */  public abstract void run();}

Let's take a look at the Declaration of the Runnable interface. After Java 8, the Runnable interface has an additional FunctionalInterface annotation, indicating that this interface is a functional interface. However, if we do not add the FunctionalInterface annotation, the compiler will treat this interface as a functional interface if there is only one abstract method in the interface.

@FunctionalInterfacepublic interface MyInterface {  void test();  String toString();}

MyInterface is also a functional interface, because toString () is a method in the Object class, but it is rewritten here and does not increase the number of abstract methods in the interface.

(Here we will mention that in Java 8, the methods in the interface can not only have abstract methods, but also have specific implementation methods, called the default method ), this section will be detailed later)

In Java, Lambda expressions are objects. So what is the object type? Let's review the SwingTest program. Here we create an ActionListener interface instance using an anonymous internal class.

jButton.addActionListener(new ActionListener() {  @Override  public void actionPerformed(ActionEvent e) {            System.out.println("Button Pressed!");  } }); 

After Lambda expressions are used

jButton.addActionListener(e -> System.out.println("Button Pressed!"));

That is, we use Lambda expressions to create an instance of the ActionListener interface. Let's look at the definition of the ActionListener interface.

public interface ActionListener extends EventListener {  /**   * Invoked when an action occurs.   */  public void actionPerformed(ActionEvent e);}

There is only one abstract method. Although the FunctionalInterface annotation is not added, it also complies with the definition of functional interfaces. the compiler will regard it as a functional interface.
Therefore, you can use Lambda expressions to create instances of function interfaces. That is, Lambda expressions return the type of functional interfaces.

In fact, there are three methods to create a function interface instance (refer to the description of the FunctionalInterface annotation ):

1. Lambda expressions
2. Method reference
3. constructor reference

Summary

The above is all about Java 8's brief introduction to Lambda expressions and functional interfaces. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message!

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.