Lambda & Method Reference

1.Lambda expression

1.1 Experience Lambda Expressions [Understanding]

  • Case requirements

    Start a thread and output a sentence in the console: The multithreaded program started

  • Mode 1

    • Implementation steps
      • Define a class MyRunnable to implement the Runnable interface and override the run() method
      • Create objects of MyRunnable class
      • Create an object of the Thread class and pass MyRunnable objects as constructor parameters
      • Start threads
  • Mode 2

    • Modification of Anonymous Internal Classes
  • Mode 3

    • Improvement of Lambda Expressions
  • Code demonstration

    //Thread class of mode one
    public class MyRunnable implements Runnable {
    
        @Override
        public void run() {
            System.out.println("Multithread program started");
        }
    }
    
    public class LambdaDemo {
        public static void main(String[] args) {
            //Mode I
    //        MyRunnable my = new MyRunnable();
    //        Thread t = new Thread(my);
    //        t.start();
    
            //Mode 2
    //        new Thread(new Runnable() {
    //            @Override
    //            public void run() {
    //                System.out.println("Multithread Program Started");
    //            }
    //        }).start();
    
            //Mode 3
            new Thread( () -> {
                System.out.println("Multithread program started");
            } ).start();
        }
    }
    
  • Overview of Functional Programming Thought

    Functional thinking tries to ignore the object-oriented complex grammar: "Emphasize what to do, not what form to do it."

    And the Lambda expression we are going to learn is the embodiment of functional thinking.

Standard Format of 1.2 Lambda Expressions [Understanding]

  • Format:

    Formal parameter - > {code block}

    • Formal parameters: If there are multiple parameters, the parameters are separated by commas; if there are no parameters, leave them blank.

    • -> It is composed of lines drawn in English and symbols larger than symbols. Represents pointing action

    • Code Block: What we need to do specifically is the content of the method we wrote before.

  • The three elements of Lambda expression are as follows:

    • Formal parameters, arrows, code blocks

1.3 Lambda Expression Exercise 1 [Application]

  • Prerequisites for the Use of Lambda Expressions

    • There is an interface

    • There is and only one abstract method in the interface

  • Exercise Description

    Exercise on abstract methods without parameters and return values

  • Operational steps

    • Define an interface (Eatable), which defines an abstract method: void eat();

    • Define a test class (EatableDemo) to provide two methods in the test class

      • One way is: use Eatable (Eatable)

      • One way is to call the useEatable method in the main method.

  • Sample code

    //Interface
    public interface Eatable {
        void eat();
    }
    //Implementation class
    public class EatableImpl implements Eatable {
        @Override
        public void eat() {
            System.out.println("An apple a day keeps the doctor away from me");
        }
    }
    //Test class
    public class EatableDemo {
        public static void main(String[] args) {
            //Call the useEatable method in the main method
            Eatable e = new EatableImpl();
            useEatable(e);
    
            //Anonymous Inner Class
            useEatable(new Eatable() {
                @Override
                public void eat() {
                    System.out.println("An apple a day keeps the doctor away from me");
                }
            });
    
            //Lambda expression
            useEatable(() -> {
                System.out.println("An apple a day keeps the doctor away from me");
            });
        }
    
        private static void useEatable(Eatable e) {
            e.eat();
        }
    }
    

1.4 Lambda Expressions Exercise 2 [Application]

  • Exercise Description

    Exercise on abstract methods with or without return values

  • Operational steps

    • Define an interface (Flyable), which defines an abstract method: void fly(String s);

    • Define a FlyableDemo and provide two methods in the test class

      • One way is to use Flyable (Flyable f)

      • One way is to call the useFlyable method in the main method

  • Sample code

    public interface Flyable {
        void fly(String s);
    }
    
    public class FlyableDemo {
        public static void main(String[] args) {
            //Call the useFlyable method in the main method
            //Anonymous Inner Class
            useFlyable(new Flyable() {
                @Override
                public void fly(String s) {
                    System.out.println(s);
                    System.out.println("Aircraft self-driving tour");
                }
            });
            System.out.println("--------");
    
            //Lambda
            useFlyable((String s) -> {
                System.out.println(s);
                System.out.println("Aircraft self-driving tour");
            });
    
        }
    
        private static void useFlyable(Flyable f) {
            f.fly("Wind and sunshine, clear sky ten thousand miles");
        }
    }
    

1.5 Lambda Expression Exercise 3 [Application]

  • Exercise Description

    Exercise on abstract methods with reference to return values

  • Operational steps

    • Define an interface (Addable), which defines an abstract method: int add(int x,int y);

    • Define a test class (AddableDemo) to provide two methods in the test class

      • One way is to use Addable (Addable a)

      • One way is to call the useAddable method in the main method

  • Sample code

    public interface Addable {
        int add(int x,int y);
    }
    
    public class AddableDemo {
        public static void main(String[] args) {
            //Call the useAddable method in the main method
            useAddable((int x,int y) -> {
                return x + y;
            });
    
        }
    
        private static void useAddable(Addable a) {
            int sum = a.add(10, 20);
            System.out.println(sum);
        }
    }
    

Ellipsis mode of 1.6 Lambda expression [application]

  • Omitted rules

    • Parameter types can be omitted. However, in the case of multiple parameters, not only one can be omitted.
    • If there is only one parameter, then parentheses can be omitted
    • If there is only one statement in the code block, braces and semicolons, and return keywords can be omitted.
  • Code demonstration

    public interface Addable {
        int add(int x, int y);
    }
    
    public interface Flyable {
        void fly(String s);
    }
    
    public class LambdaDemo {
        public static void main(String[] args) {
    //        useAddable((int x,int y) -> {
    //            return x + y;
    //        });
            //The type of parameter can be omitted
            useAddable((x, y) -> {
                return x + y;
            });
    
    //        useFlyable((String s) -> {
    //            System.out.println(s);
    //        });
            //If there is only one parameter, then parentheses can be omitted
    //        useFlyable(s -> {
    //            System.out.println(s);
    //        });
    
            //If there is only one statement in the code block, braces and semicolons can be omitted.
            useFlyable(s -> System.out.println(s));
    
            //If there is only one statement in the code block, braces and semicolons can be omitted, and if there is a return, return can also be omitted.
            useAddable((x, y) -> x + y);
        }
    
        private static void useFlyable(Flyable f) {
            f.fly("Wind and sunshine, clear sky ten thousand miles");
        }
    
        private static void useAddable(Addable a) {
            int sum = a.add(10, 20);
            System.out.println(sum);
        }
    }
    

Notes on 1.7 Lambda Expressions [Understanding]

  • Using Lambda requires an interface and requires that there is and only one abstract method in the interface.

  • In order to deduce Lambda's corresponding interface, a context environment is necessary.

    • According to the assignment of local variables, the corresponding interface of Lambda is known.

      Runnable r = () - > System. out. println ("Lambda expression");

    • The interface corresponding to Lambda is known according to the parameters of the calling method.

      New Thread (-> System. out. println ("Lambda expression"). start();

The Difference between 1.8 Lambda Expressions and Anonymous Internal Classes [Understanding]

  • Different types of requirements

    • Anonymous inner classes: they can be interfaces, Abstract classes, or concrete classes
    • Lambda expression: can only be an interface
  • Use restrictions are different

    • If there is only one abstract method in the interface, you can use Lambda expressions or anonymous inner classes.

    • If there are more than one abstract method in the interface, only anonymous inner classes can be used instead of Lambda expressions.

  • The principle of realization is different.

    • Anonymous inner class: After compilation, a separate. class bytecode file is generated
    • Lambda expression: After compilation, there is no single. class bytecode file. The corresponding bytecode is generated dynamically at run time

2. Interface Composition Update

2.1 Interface Composition Update Overview [Understanding]

  • constant

    public static final

  • Abstract method

    public abstract

  • Default Method (Java 8)

  • Static Method (Java 8)

  • Private methods (Java 9)

Default Method in 2.2 Interface [Application]

  • format

    public default return value type method name (parameter list) {}

  • Example

    public default void show3() { 
    }
    
  • Matters needing attention

    • The default method is not an abstract method, so it is not forced to be overridden. But it can be rewritten. When rewritten, the default keyword is removed.

    • public can be omitted, default can not be omitted

Static Method in 2.3 Interface [Application]

  • format

    public static return value type method name (parameter list) {}

  • Example

    public static void show() {
    }
    
  • Matters needing attention

    • Static methods can only be invoked by interface names, not by class names or object names.

    • public can be omitted, while static cannot be omitted.

Private Method in 2.4 Interface [Application]

  • Reasons for Private Approaches

    The addition of private methods with method bodies in Java 9 actually sets the stage for Java 8: Java 8 allows default and static methods with method bodies to be defined in interfaces. This may lead to a problem: when two default methods or static methods contain the same code implementation, the program must consider extracting the implementation code into a common method, which does not need to be used by others, so hide it with private, which is the increase of Java 9. Necessity of Private Method

  • Definition format

    • Format 1

      private return value type method name (parameter list) {

    • Example 1

      private void show() {  
      }
      
    • Format 2

      private static return value type method name (parameter list) {}

    • Example 2

      private static void method() {  
      }
      
  • Matters needing attention

    • The default method can call private static and non-static methods
    • Static methods can only call private static methods

3. Method Reference

3.1 Experience Method Reference [Understanding]

  • Reasons for Method Reference

    When using Lambda expressions, the code we actually pass in is a solution: manipulate parameters

    So consider a case: if we already have the same solution in place for the operation scheme specified in Lambda, is it necessary to write duplicate logic again? The answer is definitely not necessary.

    So how do we use existing solutions?

    This is the method reference we're going to talk about. We use the existing solution through the method reference.

  • Code demonstration

    public interface Printable {
        void printString(String s);
    }
    
    public class PrintableDemo {
        public static void main(String[] args) {
            //Call the usePrintable method in the main method
    //        usePrintable((String s) -> {
    //            System.out.println(s);
    //        });
    	    //Lambda's Simplified Writing
            usePrintable(s -> System.out.println(s));
    
            //Method reference
            usePrintable(System.out::println);
    
        }
    
        private static void usePrintable(Printable p) {
            p.printString("Love life love Java");
        }
    }
    
    

3.2 Method References [Understanding]

  • Method reference

    :: This symbol is a reference operator, and its expression is called a method reference.

  • Derivation and Ellipsis

    • If Lambda is used, they will be automatically deduced without specifying parameter types or overloading forms according to the principle of "deductibility is omitted".
    • If the method is referenced, it can also be deduced from the context.
    • Method citation is Lambda's twin brother

3.3 Reference Class Method [Application]

Referencing class methods is actually a static method of referencing classes.

  • format

    Class name: static method

  • Example

    Integer::parseInt

    Method of Integer class: public static int parseInt(String s) converts this String to int-type data

  • Exercise Description

    • Define an interface (Converter), which defines an abstract method int convert(String s);

    • Define a Converter Demo to provide two methods in the test class

      • One way is to use Converter (Converter c)

      • One way is to call the useConverter method in the main method.

  • Code demonstration

    public interface Converter {
        int convert(String s);
    }
    
    public class ConverterDemo {
        public static void main(String[] args) {
    
    		//Lambda Writing
            useConverter(s -> Integer.parseInt(s));
    
            //Reference Class Method
            useConverter(Integer::parseInt);
    
        }
    
        private static void useConverter(Converter c) {
            int number = c.convert("666");
            System.out.println(number);
        }
    }
    
  • Instructions

    When Lambda expression is replaced by class method, its formal parameters are all passed to static method as parameters.

3.4 Example Method of Referencing Objects [Application]

Referencing an instance method of an object actually refers to a member method in a class.

  • format

    Object: Membership method

  • Example

    "HelloWorld"::toUpperCase

    Method in String class: public String to UpperCase () converts all characters of this String to uppercase

  • Exercise Description

    • Define a class (PrintString), which defines a method

      Public void print Upper (String): Change string parameters to uppercase data, and then output it in the console

    • Define an interface (Printer), which defines an abstract method

      void printUpperCase(String s)

    • Define a test class (PrinterDemo) and provide two methods in the test class

      • One way is to use Printer (Printer p)
      • One way is to call the usePrinter method in the main method
  • Code demonstration

    public class PrintString {
        //Change string parameters to uppercase data and output them in the console
        public void printUpper(String s) {
            String result = s.toUpperCase();
            System.out.println(result);
        }
    }
    
    public interface Printer {
        void printUpperCase(String s);
    }
    
    public class PrinterDemo {
        public static void main(String[] args) {
    
    		//Lambda's Simplified Writing
            usePrinter(s -> System.out.println(s.toUpperCase()));
    
            //Instance method of reference object
            PrintString ps = new PrintString();
            usePrinter(ps::printUpper);
    
        }
    
        private static void usePrinter(Printer p) {
            p.printUpperCase("HelloWorld");
        }
    }
    
    
  • Instructions

    When Lambda expression is replaced by instance method of object, its formal parameters are all passed to this method as parameters.

3.5 Instance Method of Reference Class [Application]

An instance method of a reference class is actually a member method of a reference class.

  • format

    Class name: member method

  • Example

    String::substring

    public String substring(int beginIndex,int endIndex)

    From beginIndex to endIndex, intercept the string. Returns a substring whose length is endIndex-beginIndex

  • Exercise Description

    • Define an interface (MyString), which defines an abstract method:

      String mySubString(String s,int x,int y);

    • Define a test class (MyStringDemo) that provides two methods in the test class

      • One way is to use MyString (MyString my)

      • One way is to call the useMyString method in the main method

  • Code demonstration

    public interface MyString {
        String mySubString(String s,int x,int y);
    }
    
    public class MyStringDemo {
        public static void main(String[] args) {
    		//Lambda's Simplified Writing
            useMyString((s,x,y) -> s.substring(x,y));
    
            //Instance method of reference class
            useMyString(String::substring);
    
        }
    
        private static void useMyString(MyString my) {
            String s = my.mySubString("HelloWorld", 2, 5);
            System.out.println(s);
        }
    }
    
  • Instructions

    When Lambda expressions are replaced by instance methods of classes
    The first parameter acts as the caller
    The latter parameters are all passed to the method as parameters

3.6 Reference Constructor [Application]

A reference constructor is actually a reference constructor

  • l format

    Class name::new

  • Example

    Student::new

  • Exercise Description

    • Define a class (Student) with two member variables (name,age)

      The parametric construction method and parametric construction method as well as the corresponding get and set methods of member variables are also provided.

    • Define a Student Builder, which defines an abstract method

      Student build(String name,int age);

    • Define a Student Demo to provide two methods in the test class

      • One way is: use Student Builders (Student Builders)

      • One way is to call the useStudentBuilder method in the main method

  • Code demonstration

    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    
    public interface StudentBuilder {
        Student build(String name,int age);
    }
    
    public class StudentDemo {
        public static void main(String[] args) {
    
    		//Lambda's Simplified Writing
            useStudentBuilder((name,age) -> new Student(name,age));
    
            //Reference constructor
            useStudentBuilder(Student::new);
    
        }
    
        private static void useStudentBuilder(StudentBuilder sb) {
            Student s = sb.build("Lin Qingxia", 30);
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
    
  • Instructions

    When Lambda expression is replaced by constructor, its formal parameters are all passed to constructor as parameters.

Keywords: Lambda Java Programming

Added by Kemik on Thu, 15 Aug 2019 14:23:55 +0300