java_ Method references in lambda expressions

Method reference

When we use lambda, if there is only one method call in the method body (including the construction method), we can use method references to further simplify the code.

It is also a grammar sugar
Know what it means. You can read other people's code
Write more and become proficient. You can use shortcut keys to develop for shortcut keys

Basic format

Class name or object name:: method name

1. static method of reference class

format
Class name::Method name
Premise of use

If there is only one line of code in the method body when we rewrite a method, and this line of code calls a static method of a class, and we pass all the parameters in the abstract method to be rewritten into the static method in order, then we can reference the static method of the class.

For example:

The following code can be simplified with method references

        List<Author> authors = getAuthors();

        Stream<Author> authorStream = authors.stream();
        
        authorStream.map(author -> author.getAge())
                .map(age->String.valueOf(age));

Note that if the method we rewrite has no parameters, the method we call also has no parameters, which is equivalent to complying with the above rules.

Optimized as follows:

        List<Author> authors = getAuthors();

        Stream<Author> authorStream = authors.stream();

        authorStream.map(author -> author.getAge())
                .map(String::valueOf);

2. instance method of reference object

format
Object name::Method name
Premise of use

If there is only one line of code in the method body when we rewrite the method, and this line of code calls the member method of an object, and we pass all the parameters in the abstract method to be rewritten into the member method in order, then we can reference the instance method of the object

For example:

        List<Author> authors = getAuthors();

        Stream<Author> authorStream = authors.stream();
        StringBuilder sb = new StringBuilder();
        authorStream.map(author -> author.getName()) //You can't use dissatisfaction here: all parameters in the abstract method are passed into the member method in sequence
                .forEach(name->sb.append(name));

After optimization:

        List<Author> authors = getAuthors();

        Stream<Author> authorStream = authors.stream();
        StringBuilder sb = new StringBuilder();
        authorStream.map(author -> author.getName())
                .forEach(sb::append);

3. instance method of reference class

format
Class name::Method name
Premise of use

If there is only one line of code in the method body when we rewrite the method, and this line of code is a member method that calls the first parameter, and we pass all the remaining parameters in the abstract method to be rewritten into the member method in order, then we can reference the instance method of the class.

public class MethDemo {
    interface UseString{
        String use(String str,int start,int length);
    }

    public static String subAuthorName(String str, UseString useString){
        int start = 0;
        int length = 1;
        return useString.use(str,start,length);
    }

    public static void main(String[] args) {
        subAuthorName("Sangeng cottage", new UseString() {
            @Override
            public String use(String str, int start, int length) {
                return str.substring(start,length);
            }
        });

        subAuthorName("Sangeng cottage", String::substring);

    }

}
books.ifPresent(System.out::println);

4. constructor reference

Constructor references can be used if a line of code in the method body is a constructor.

format
Class name::new
Premise of use

If there is only one line of code in the method body when we rewrite a method, and this line of code calls the constructor of a class, and we pass all the parameters in the abstract method to be rewritten into the constructor in order, then we can reference the constructor.

For example:

        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getName())
                .map(name->new StringBuilder(name))
                .map(sb->sb.append("-AAA").toString())
                .forEach(str-> System.out.println(str));

After optimization:

        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getName())
                .map(StringBuilder::new)
                .map(sb->sb.append("-AAA").toString())
                .forEach(str-> System.out.println(str));

Lambda is used to reduce the confusion of various calls of anonymous inner classes. Method reference is used to further simplify lambda. So the readability is poor

Tags: Java

Posted by OzRedBoy on Sat, 04 Jun 2022 01:51:18 +0530