Detailed explanation of Lambda expression in Java

  • 2021-07-16 02:19:12
  • OfStack

Brief introduction

Lambda expression is an important new feature in Java SE 8. lambda expressions allow you to use expressions instead of functional interfaces. The lambda expression is like Method 1, which provides a normal list of parameters and a body that uses them (body, which can be an expression or a block of code).

The Lambda expression also enhances the collection library. Java SE 8 adds two packages for bulk operations on aggregate data: java. util. function and java. util. stream. Stream (stream) is just like iterator (iterator), but with many additional functions. Overall, the lambda expression and stream are the biggest changes since the Java language added generics (Generics) and annotations (annotation).

Lambda comes from the Greek alphabet and is pronounced/'l & aelig; md/

Anyone who knows something about high numbers knows that λ is used to declare a mathematical logic system, which means that some Y result will be returned according to the input parameters of XX. This is what functions (methods) mean in programming languages.

Therefore, Lambda expression is a method expression in programming language.

Why do you want to come up with such a thing? This is because our programming languages are all designed for object-oriented, that is, I give you a few objects and you return a few objects to me, but sometimes we just pass some algorithmic logic around. You don't need such a complete structure as an object.

OO language commonly used to write this algorithm logic as a method in the object, and then pass the object around. This is fine, but it is not developer-friendly, and sometimes difficult to read because of the amount of redundant code. Therefore, the designer of the programming language came up with such an Lambda expression, which allows the algorithm logic (method) to be passed as a transitive object.
Lambda expressions have appeared in other languages for a long time, such as Lisp and C # (The advantages of C # design have to be mentioned here, which also shows that it is very difficult to design a programming language. The design is ahead of schedule, and many people may not know how to use it. The design lags behind, and many people disdain to use it. Java was introduced in Jdk 8 to help java developers get rid of redundant code development.
Before we talk about Lambda expressions, we should introduce one concept:

Functional interface

What is a functional interface?

It is an interface that only defines one abstract method. We can use the annotation @ Functionallnterface to strongly constrain this interface as a functional interface.

You can look at the source code of jdk8, such as Runnable, Callable, Comparator and other early interfaces have added this annotation.

Lambda expressions are expressions specifically designed to implement these functional interfaces, which is very important.


 @FunctionalInterface
 public interface Runnable {
   public abstract void run();
 }

Let's get down to business. How should we write Lambda expressions?

If we want to start a thread with Runnable, we need to write this:


 Runnable runnable = new Runnable()
 {
    @Override
    public void run()
    {
      // TODO
    }
 };
 new Thread(runnable).start();

That is to say, an internal anonymous class implements the methods in the interface, and then operates. Its essence is to include a piece of logic in run method and throw it to the thread for execution.
However, the Lambda expression can be directly used as a function expression to replace this inner class.


 Runnable runnable = ()->
 {
  // dosth
  };
 new Thread(runnable).start();

In this example, we can find that the Lambda representation consists of three parts:

1. Parameter list: It is the same as the parameter list requirement 1 of the method in the interface

2. Arrow:- > Consists of a horizontal line and a greater than sign

3. Method body: The method body requirements of the method are the same as those of the method.

At the same time, Lambda has made the following improvements for simplicity (anti-theft connection: this article started from http://www.cnblogs.com/jilodream/):

1. Parameter types in the parameter list can be ignored without writing. (Note that it is a parameter type, not a parameter. Because there is only one abstract method, the parameter type can be directly derived.)

2. If there is only one parameter, parentheses can also be omitted.

3. If there is only 1 statement in the method body, curly braces can be omitted.

4. If there is only one statement and it is an return statement, the return keyword can be omitted directly.

Look directly at the following example:


 import java.util.List;
 @FunctionalInterface
 public interface ICommand
 {
   List<Integer> process(Integer[] target);
 }

 import java.util.List;
 
 public class ProcessArray
 {
   public List<Integer> process(Integer[] target, ICommand cmd)
   {
     return cmd.process(target);
   }
 }

import java.util.Arrays;
 import java.util.List; 
 public class JavaLambda
 {
   public static void main(String[] args)
   {
     ICommand cmd = tt -> Arrays.asList(tt);
     ProcessArray processArray = new ProcessArray();
     List<Integer> list2 = processArray.process(new Integer[]
     { 1, 2, 3, 4, 5, 6, 7 }, cmd);
   }
 }

We can find that in the JavaLambdal class, at line 8, to the right of the equal sign:

1. No type of parameter declared

2. Parentheses without parameter list

3. Method body without curly braces

4. Method body does not have return keyword

Summarize


Related articles: