Preface

Prepare for the job hopping interview , Today we begin to enter Java Basic review . I hope students with poor foundation will finish reading this article , Can master lambda expression , And the students with good foundation should have the right to review , I hope that after reading this article, you can have a little green memory .

One 、 What is? lambda expression

Java8 It's our most widely used stable Java edition ,lambda It's one of the most remarkable new features .lambda It's a closure , It allows functions to be used as parameters , It's the idea of functional programming , Can make the code look more concise . I wonder if I can't hear it ? I'll give you a chestnut and you'll see .

Examples of rotten teeth , In the absence of lambda When , This is how we write :

//  Internal class writing 
public class InnerClassMain {
    public static void main(String[] args) {
        // Anonymous inner class writing 
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(" Internal class writing ");
            }
        }).start();
    }
}

Yes lambda after , We will use lambda Write :

// lambda  How to write it 
public class LambdaMain {
    
    public static void main(String[] args) {
        //lambda  How to write it 
        new Thread(() -> System.out.println("lambda How to write it ")).start();
    }
    
}

We should know , There are two ways to implement threads , One is inheritance Thread class , Two is the realization. Runnable Interface . The latter is used here , The latter is a functional interface .

1.1 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();
}

from Runnable Source code can be seen , It's a functional interface . The characteristic of this kind of interface is : use @FunctionalInterface To modify ( Mainly used for compile level error checking , Add the note , When you write an interface that doesn't fit the functional interface definition , The compiler will report an error ), There is and only one abstract method . In a native JDk This kind of interface in can be used lambda expression .

The above concept refers to , Use functions as arguments . above lambda In the example ,Thread The parameter of the class is a Runnable Interface ,lambda That is to implement this interface and use it as a parameter . So the top () -> System.out.println("lambda How to write it ") It's a whole lambda The argument to the expression ( Note the distinction from the method parameters that follow , The back can speak ). Fine and bold , It can be concluded that ,lambda An expression is an instance object that creates a functional interface of a class . Such as :

Runnable runnable = () -> System.out.println("lambda How to write it ");

Two 、 Why lambda expression

Got it  lambda expression , So why use it ? Notice the use of lambda When creating a thread , We don't care about interface names , Method name , Parameter name . We only focus on its parameter types , Number of parameters , Return value . So the reason is to simplify the code , Improve readability .

3、 ... and 、 How to use lambda expression

3.1 lambda grammar

//  Format follows : ( Interface parameters )-> expression ( The specific implementation method )
(paramters) -> expression  or  (parameters) ->{ expressions; }

lambda  Examples of grammar

Specific explanation , Pictured above . Besides ,lambda Grammar points for attention :

  • Optional type declaration : Method parameters do not need to declare parameter types , Compiler can identify parameter values uniformly .
  • Optional parameter parentheses : A parameter does not need to define parentheses , But no parameters or more parameters need to be defined in parentheses .
  • Optional braces : If the specific implementation method has only one statement , You don't need to use brackets {}.
  • Optional return key : If there is only one expression for the specific implementation method , The compiler will automatically return the value , If there are multiple expressions, then , Brackets need to specify that the expression returns a value .

Examples of use :

public class Example {

    //  Define functional interfaces , There can only be one abstract interface , Otherwise, an error will be reported 
    //  I hope to check out the error report at compile time , Please add  @FunctionalInterface  annotation 
    public interface Hello {
        String hi();
    }

    public interface Hello2 {
        String hei(String hello);
    }

    public interface Hello3 {
        String greet(String hello, String name);
    }

    public static void main(String[] args) {

        //  The parameter is empty 
        Hello no_param = () -> "hi, no param";
        Hello no_param2 = () -> {
            return "hi, no param";
        };

        System.out.println(no_param.hi());
        System.out.println(no_param2.hi());

        //  Single parameter , A return statement , You can omit braces and  return
        Hello2 param = name -> name;
        Hello2 param2 = name -> {
            return name;
        };

        //  Print 
        System.out.println(param.hei("hei,  A good loser "));
        System.out.println(param2.hei("hei,  A good loser "));

        //  Multiple parameters 
        Hello3 multiple = (String hello, String name) -> hello + " " + name;

        //  A return statement , You can omit braces and  return
        Hello3 multiple2 = (hello, name) -> hello + name;

        //  Multiple processing statements , You need braces and  return
        Hello3 multiple3 = (hello, name) -> {
            System.out.println("  Go inside  ");
            return hello + name;
        };

        //  Print 
        System.out.println(multiple.greet("hello,", " I wish 2020 Take off a single "));
        System.out.println(multiple2.greet("hello,", " I wish 2020 Take off a single "));
        System.out.println(multiple3.greet("hello,", " I wish 2020 Take off a single "));
    }
}

3.3 Method reference

Look at a simple method quote example :

Consumer<String> sc = System.out::println;
sc.accept(" A good loser ");

//  Equivalent to 
Consumer<String> sc2 = (x) -> System.out.println(x);
sc2.accept(" A good loser ");

Consumer Functional interface source code :

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

You may be a little confused , Why can I write like this ? Don't worry, let's analyze a wave :Consumer

public class ConsumerImpl implements Consumer<String> {
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
}

After implementation , The abstract method becomes concrete . The function is to print on the console , That means that the abstract method can just use the practical method : System.out.println(s) To achieve , So we can use method references .

summary : The abstract method of functional interface can be realized by calling an actual method , You can use methods to reference .

Three forms of method references :

//  Use abstract method parameters as actual method parameters 
 object :: Example method  objectName::instanceMethod
//  Use abstract method parameters as actual method parameters 
 class :: Static methods  ClassName::staticMethod
//  Treat the first parameter of a method parameter as the caller of the method , Other parameters are used as parameters of the method 
 class :: Example method   ClassName::instanceMethod

Customize a method class :

public class Method {
    //  Static methods 
    public static void StaticMethod(String name) {
        System.out.println(name);
    }

    //  Example method 
    public void InstanceMethod(String name) {
        System.out.println(name);
    }

    //  Nonparametric construction method 
    public Method() {
    }

    //  There are parametric constructions 
    public Method(String methodName) {
        System.out.println(methodName);
    }
}

The test case :

public class MethodExample {

    public static void main(String[] args) {

        //  Static method reference -- Called by the class name 
        Consumer<String> consumerStatic = Method::StaticMethod;
        consumerStatic.accept(" Static methods ");
        //  Equivalent to 
        Consumer<String> consumerStatic2 = (x) -> Method.StaticMethod(x);
        consumerStatic2.accept(" Static methods ");

        System.out.println("--------------------------");
        // Non static method references -- Call... By instance 
        Method method = new Method();
        Consumer<String> consumerInstance = method::InstanceMethod;
        consumerInstance.accept(" The instance method of the object ");
        //  Equivalent to 
        Consumer<String> consumerInstance2 = (x) -> method.InstanceMethod(x);
        consumerInstance2.accept(" The instance method of the object ");

        System.out.println("--------------------------");
        //ClassName::instanceMethod   class : Think of the first parameter of the expression as  instanceMethod  The caller , Other parameters are used as parameters of the method 
        BiPredicate<String, String> sbp = String::equals;
        System.out.println(" class  " + sbp.test("a", "A"));
        //  equivalent 
        BiPredicate<String, String> sbp2 = (x, y) -> x.equals(y);
        System.out.println(" class  " + sbp2.test("a", "A"));
    }
}

Output results :

 Static methods 
 Static methods 
--------------------------
 The instance method of the object 
 The instance method of the object 
--------------------------
 class false
 class false

3.4 Constructor reference

public class ConstructMethodExample {

    public static void main(String [] args) {
        //  Constructor method reference -- No parameter ( You can use methods to reference )
        Supplier<Method> supplier = Method::new;
        System.out.println(supplier.get());
        //  Equivalent to 
        Supplier<Method> supplier2 = () -> new Method();
        System.out.println(supplier2.get());

        //  Constructor method reference -- With parameters 
        Function<String, Method> uf = name -> new Method(name);
        Method method = uf.apply(" A good loser ");
        System.out.println(method.toString());
    }

}
  • Reference resources :https://www.cnblogs.com/kingsonfu/p/11047116.html

3.5 Variable scope

lambda Expressions can only refer to tags final The outer local variable of , That is to say, it can't be in lambda Internal modification of local variables defined outside the domain , Otherwise it will compile incorrectly .

public class VariableScopeTest {

    //  Define an interface 
    public interface Converter<T1, T2> {
        void convert(int i);
    }
    
    public static void main(String [] args) {

        //  Defined as  final  Force cannot be modified 
        final int num = 1;
        Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
        //  The output is  3
        s.convert(2);  
    }

}

Variables are not declared as final , Cause can modify external variable to report error :

int num = 1;
Converter<Integer, String> s = (param) -> System.out.println(String.valueOf(param + num));
s.convert(2);

Besides , stay Lambda It is not allowed to declare a parameter or local variable with the same name as the local variable in an expression

String first = "";  
//  A fellow  first  Variable name , Compilation error  
Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length());

Four 、 top ten lambda Examples of expressions

  • Example :https://blog.csdn.net/qq_37176126/article/details/81273195

  • Github Source code address ( I think it's good , Give me one star Chant ):https://github.com/turoDog/review_java/tree/master/src/main/java/com/nasus/lambda

5、 ... and 、 Source code address

  • github Source code address :https://github.com/turoDog/review_java

If you see this , Like this article , Help " forward " Or order " Looking at ", Would you? ? I wish you all the best 2020 A rich man . WeChat search 「 A good loser 」, Welcome to your attention .

reply 「1024」 Send you a complete set java、python、c++、go、 front end 、linux、 Algorithm 、 big data 、 Artificial intelligence 、 Small program and English Course .

reply 「 e-book 」 Send you 50+ Ben java e-book .

 Most comprehensive tutorial

 A good loser