Day22 lambda & method reference - new features of JDK

1.Lambda expression

1.1 experience Lambda expression [understanding]

  • Case requirements

    Start a thread and output a sentence on the console: the multithreaded program is started

  • Implementation mode I

    • Implementation steps
      • Define a class MyRunnable, implement the Runnable interface, and override the run() method
      • Create an object of the MyRunnable class
      • Create an object of Thread class and pass the object of MyRunnable as a construction parameter
      • Start thread
  • Implementation mode 2

    • Improvement of anonymous inner class
  • Implementation mode III

    • Improvement of Lambda expression
  • Code demonstration

    //Thread class of mode 1
    public class MyRunnable implements Runnable {
    
        @Override
        public void run() {
            System.out.println("The multithreaded program started");
        }
    }
    
    public class LambdaDemo {
        public static void main(String[] args) {
            //Mode 1
    //        MyRunnable my = new MyRunnable();
    //        Thread t = new Thread(my);
    //        t.start();
    
            //Mode II
    //        new Thread(new Runnable() {
    //            @Override
    //            public void run() {
    //                System.out.println("multithreaded program started");
    //            }
    //        }).start();
    
            //Mode III
            new Thread( () -> {
                System.out.println("The multithreaded program started");
            } ).start();
        }
    }
    
  • Overview of functional programming ideas

    Functional thinking tries to ignore the complex object-oriented syntax: "emphasize what to do, not what form to do"

    The Lambda expression we want to learn is the embodiment of the idea of functional expression

1.2 standard format of lambda expression [understanding]

  • Format:

    (formal parameter) - > {code block}

    • Formal parameters: if there are multiple parameters, the parameters are separated by commas; If there is no parameter, just leave it blank

    • ->: it is composed of lines drawn in English and greater than symbol, with fixed writing method. Represents pointing action

    • Code block: it is the specific thing we need to do, that is, the content of the method body we wrote before

  • Three elements that make up a Lambda expression:

    • Formal parameter, arrow, code block

1.3 lambda expression exercise 1 [application]

  • Premise of Lambda expression

    • There is an interface

    • There is only one abstract method in the interface

  • Exercise description

    Practice of parameter free and return value free abstract method

  • Operation steps

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

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

      • One method is: use eatable (eatable E)

      • One method is the main method, and the useEatable method is called 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");
        }
    }
    //Test class
    public class EatableDemo {
        public static void main(String[] args) {
            //Calling 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");
                }
            });
    
            //Lambda expression
            useEatable(() -> {
                System.out.println("An apple a day keeps the doctor away");
            });
        }
    
        private static void useEatable(Eatable e) {
            e.eat();
        }
    }
    

1.4 lambda expression exercise 2 [application]

  • Exercise description

    Exercises on abstract methods with parameters and no return values

  • Operation steps

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

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

      • One method is: use flyable (flyable f)

      • One method is the main method, and the useFlyable method is called in the main method.

  • Sample code

    public interface Flyable {
        void fly(String s);
    }
    
    public class FlyableDemo {
        public static void main(String[] args) {
            //Calling 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("Plane self driving tour");
                }
            });
            System.out.println("--------");
    
            //Lambda
            useFlyable((String s) -> {
                System.out.println(s);
                System.out.println("Plane self driving tour");
            });
    
        }
    
        private static void useFlyable(Flyable f) {
            f.fly("The wind is sunny and the sky is clear");
        }
    }
    

1.5 lambda expression exercise 3 [application]

  • Exercise description

    Exercises on abstract methods with parameters and return values

  • Operation steps

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

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

      • One method is: use addable (addable a)

      • One method is the main method, and the useAddable method is called in the main method.

  • Sample code

    public interface Addable {
        int add(int x,int y);
    }
    
    public class AddableDemo {
        public static void main(String[] args) {
            //Calling 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);
        }
    }
    

1.6 omission mode of lambda expression [application]

  • Omitted rules

    • Parameter types can be omitted. However, when there are multiple parameters, you cannot omit only one
    • If there is only one parameter, the parentheses can be omitted
    • If the code block has only one statement, you can omit braces, semicolons, and the return keyword
  • 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, the parentheses can be omitted
    //        useFlyable(s -> {
    //            System.out.println(s);
    //        });
    
            //If the code block has only one statement, you can omit braces and semicolons
            useFlyable(s -> System.out.println(s));
    
            //If there is only one statement in the code block, you can omit braces and semicolons. If there is a return, return should also be omitted
            useAddable((x, y) -> x + y);
        }
    
        private static void useFlyable(Flyable f) {
            f.fly("The wind is sunny and the sky is clear");
        }
    
        private static void useAddable(Addable a) {
            int sum = a.add(10, 20);
            System.out.println(sum);
        }
    }
    

1.7 precautions for lambda expression [understanding]

  • To use Lambda, there must be an interface, and there must be only one abstract method in the interface

  • The interface corresponding to Lambda can be deduced only if there is a context

    • The interface corresponding to Lambda is known according to the assignment of local variables

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

1.8 differences between lambda expressions and anonymous inner classes [understanding]

  • Different types required

    • Anonymous inner class: it can be an interface, an abstract class, or a concrete class
    • Lambda expression: can only be an interface
  • Different use restrictions

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

    • If there is more than one abstract method in the interface, only anonymous inner classes can be used, not Lambda expressions

  • Different implementation principles

    • Anonymous inner class: after compilation, a separate. Class bytecode file is generated
    • Lambda expression: after compilation, there is no separate. class bytecode file. The corresponding bytecode will be generated dynamically during operation

2. Interface composition update

2.1 overview of interface composition update [understanding]

  • constant

    public static final

  • Abstract method

    public abstract

  • Default method (Java 8)

  • Static method (Java 8)

  • Private method (Java 9)

2.2 default method in 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 rewriting, remove the default keyword

    • public can be omitted, but default cannot be omitted

2.3 static method in 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 called through the interface name, not through the implementation class name or object name

    • public can be omitted, but static cannot be omitted

2.4 private method in interface [application]

  • Causes of private methods

    The private method with method body is added in Java 9, which actually lays the groundwork in Java 8: Java 8 allows the default method and static method with method body to be defined in the interface. This may lead to a problem: when two default methods or static methods contain the same code implementation, the program must consider extracting this implementation code into a common method, and this common method does not need to be used by others. Therefore, it is necessary to hide it with private. This is the necessity of adding private methods in Java 9

  • Define 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 ]

  • Reason for occurrence of method reference

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

    Then consider a case: if the same scheme already exists in the operation scheme specified in Lambda, is it necessary to write duplicate logic? The answer must be no need

    How do we use the existing scheme?

    This is the method reference we want to explain. We use the existing scheme through method reference

  • Code demonstration

    public interface Printable {
        void printString(String s);
    }
    
    public class PrintableDemo {
        public static void main(String[] args) {
            //Calling the usePrintable method in the main method
    //        usePrintable((String s) -> {
    //            System.out.println(s);
    //        });
    	    //Lambda simplified writing method
            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 reference character [understanding]

  • Method reference

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

  • Derivation and omission

    • If Lambda is used, according to the principle of "derivable is omitted", there is no need to specify the parameter type or overload form, and they will be derived automatically
    • If a method reference is used, it can also be deduced according to the context
    • Method references are Lambda's twin brothers

3.3 reference method [application]

A reference class method is actually a static method of a reference class

  • 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 test class (ConverterDemo) and provide two methods in the test class

      • One method is: useConverter(Converter c)

      • One method is the main method, and the useConverter method is called 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 a Lambda expression is replaced by a class method, all its formal parameters are passed to the static method as parameters

3.4 instance method of reference object [ application ]

The instance method of a reference object actually refers to the member method in the class

  • format

    Object:: member method

  • example

    "HelloWorld"::toUpperCase

    The method in the String class: public String toUpperCase() converts all characters of this String to uppercase

  • Exercise description

    • Define a class (PrintString) that defines a method

      public void printUpper(String s): change the string parameter to uppercase data, and then output it on 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 method is: usePrinter(Printer p)
      • One method is the main method, and the usePrinter method is called in the main method.
  • Code demonstration

    public class PrintString {
        //Change the string parameter to uppercase data, and then output it on 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 simplified writing method
            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 a Lambda expression is replaced by an instance method of an object, all its formal parameters are passed to the 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)

    Intercept the string from beginIndex to endIndex. 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) and provide two methods in the test class

      • One method is: use mystring (mystring my)

      • One method is the main method, and the useMyString method is called 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 simplified writing method
            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 a Lambda expression is replaced by an instance method of a class
    The first parameter is the caller
    All the following parameters are 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)

      It also provides parameterless construction methods and parameterless construction methods, as well as get and set methods corresponding to member variables

    • Define an interface (StudentBuilder) that defines an abstract method

      Student build(String name,int age);

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

      • One method is: use studentbuilder (studentbuilder s)

      • One method is the main method, and the useStudentBuilder method is called 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 simplified writing method
            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 a Lambda expression is replaced by a constructor, all its formal parameters are passed to the constructor as parameters

Tags: Java Scala java web

Posted on Mon, 20 Sep 2021 10:34:14 -0400 by kostik