How to understand the lambda expression in java

Keywords: Lambda Java Python Programming

1. From polymorphism

Polymorphism in java enables us to create an instance for variables of interface type, that is, to create objects of interface implementation class. For example, define an add interface and an implementation class of the interface

  • Add interface:
public interface IAdd {
    int add(int a,int b);
}
  • Add implementation class:
public class Add implements IAdd {
    @Override
    public int add(int a, int b) {
        return a+b;
    }
}
  • Examples of creating interface variables in polymorphism:
public class lambdaTest {
    public void test1(){
        IAdd add = new Add;
    }
}

2. Can the interface be new directly? You do not want to create a subclass assignment to the interface reference.

Sure. Because the anonymous inner class new interface can be used, the interface implementation class object is also created in essence, but no name is given.

  • Anonymous inner class:
public class lambdaTest {
    @Test
    public void test1(){
        IAdd add = new IAdd() {
            @Override
            public int add(int a, int b) {
                return a+b;
            }
        };
        System.out.println(add.add(5,3));
    }
	//8
}

Anonymous inner class can be used if the implementation class is not used repeatedly, but the code of anonymous inner class is not concise enough.

3. lambda expression is used to replace anonymous inner class

Anonymous inner class, which rewrites the abstract method of the interface after the new interface. If there is only one abstract method in the interface, the method name can not be specified when rewriting this method. At this point, the lambda expression comes out.

Lambda expression is a kind of functional programming idea, which was introduced after java 1.8. java is an object-oriented language, everything is object-oriented, and lambda expression surface looks like a mathematical function. It looks like this:

(parameter a, parameter b,...) - > {function body}

lambda expression:

 @Test
    public void test(){
        IAdd add=(int a,int b)->{return a+b;};
        System.out.println(add.add(5,6));
    }

To sum up, you can see that lambda expressions can replace anonymous inner classes with only one method. From the thought of polymorphism to the realization of lambda expression, we can see that the class name of the implementation class is hidden, so there is an anonymous inner class. If there is only one method of the anonymous inner class, and the method name is also hidden, there is a lambda expression.

4. Functional interface

Definition: for an interface with only one abstract method, a Lambda expression can be provided when the object of the interface is needed. This interface is called a functional interface.

java provides annotation @ functional interface to mark an interface as a function as an interface. There is only one abstract method in the mandatory interface that can be used to receive lambda expressions.
In order to avoid the complexity of the language, java does not add a variable of function type. Lambda expression is actually an interface type. When the parameters of some methods are function interface type variables, a lambda expression can be passed in. From a macro perspective, it seems that a function is passed in as the parameters of the method.

5. The case of using lambda expression in multithreading

In the case of multithreading, create an api for a new thread:

public Thread(Runnable target, String name)

Open Runnable and you can see that it is a functional interface

@FunctionalInterface
public 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();
}

Therefore, when creating a thread class, the first construction parameter can use a lambda expression.

  1. Create a class to execute
public class EarnMoney {
    private int sum=0;
    private Lock lock=new ReentrantLock();
    public void earnMoney(){
        lock.lock();
        try {
            sum+=1;
            System.out.println(Thread.currentThread().getName()+"I've earned 1 yuan, now it's all"+sum+"Piece of money");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
            System.out.println();
        }
    }
}
  1. To create variables in multiple thread operation classes, lambda expressions are used to replace instance objects or anonymous inner classes for the location of Runnable parameters. The code becomes very concise.
	@Test
    public void test3(){
        EarnMoney earnMoney = new EarnMoney();
        new Thread(() -> {earnMoney.earnMoney();},"father").start();
        new Thread(() -> {earnMoney.earnMoney();},"mother").start();
        new Thread(() -> {earnMoney.earnMoney();},"son").start();
        /**
         father I've earned 1 yuan, now it's 1 yuan in all
         mother I've earned 1 yuan, and now I've got 2 yuan in all
         son I made 1 yuan, now it's 3 yuan in total
         */
    }

Python often says that java can accomplish the same thing in ten lines of code (in fact, depending on what field, python can't replace java for the time being if it is concise in the web field). After the introduction of lambda expression, java has greatly reduced the amount of code.

Published 8 original articles, won praise 10, visited 3502
Private letter follow

Posted by tat on Fri, 06 Mar 2020 23:25:45 -0800