Basic introduction to method reference

Method reference:

When using Lambda expressions, the code we actually pass in is a solution: take what parameters to do. Then consider a situation: If the operation plan specified in Lambda already has the same plan in some places, is it necessary to write duplicate logic?

1. Redundant Lambda scene

Look at a simple functional interface to apply Lambda expressions:
example:

/*
    定义一个打印的函数式接口
*/
@FunctionalInterface
public interface Printable {
    
    
    //定义字符串的抽象方法
    void print(String s);
}

public class Demo01Printable {
    
    
    //定义一个方法,参数传递Printable接口,对字符串进行打印
    public static void printString(Printable p){
    
    
        p.print("HelloWorld");
    }

    public static void main(String[] args) {
    
    
        //调用printString方法,方法的参数Printable是一个函数式接口,所以可以传递Lambda
        printString(s-> System.out.println(s));
	}
}

The printString method only calls the print method of the Printable interface, regardless of where the specific implementation logic of the print method will print the string. The main method specifies the specific operation scheme of the functional interface Printable through the Lambda expression: After getting the String (type can be deduced, so it can be omitted) data, output it in the console.

2. Problem analysis

The problem with this code is that the operation scheme for console printing and output of strings clearly has a ready-made implementation, which is the println(String) method in the System.out object. Since what Lambda hopes to do is to call the println(String) method, why call
it manually ?

3. Use method references to improve code

Analysis:
The purpose of the Lambda expression is to print the string passed by
the parameter. The parameter s is passed to the System.out object, and the method println in the out object is called to output the string

        注意:
            1.System.out对象是已经存在的
            2.println方法也是已经存在的
        所以我们可以使用方法引用来优化Lambda表达式
        可以使用System.out方法直接引用(调用)println方法

Improve the code:

public class Demo01Printable {
    
    
    //定义一个方法,参数传递Printable接口,对字符串进行打印
    public static void printString(Printable p){
    
    
        p.print("HelloWorld");
    }

    public static void main(String[] args) {
    
    
        //调用printString方法,方法的参数Printable是一个函数式接口,所以可以传递Lambda
        printString(System.out::print);
    }
}

Program demonstration:
Insert picture description here
Note : The double colon :: writing method is called "method reference", and double colon is a new syntax.

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/109161133