## One 、Lambda An introduction to the expression - Lambda The expression is Java8 One of the most important new features in . Use Lambda Express Can replace an interface implementation with only one abstract function , Farewell to anonymous inner classes , Code to see It's easier to understand .Lambda The expression also enhances pairs of sets 、 Iteration of the framework 、 Traversal 、 The operation of filtering data . - lambda A representation can replace an interface implementation with only one abstract function , Farewell to anonymous inner classes , The code looks simpler and easier to understand - lambda The expression also enhances pairs of sets 、 Iteration of the framework 、 Traversal 、 The operation of filtering data - lambda Can greatly reduce code redundancy , At the same time, the readability of the code is better than that of lengthy inner classes , Anonymous class For example, we used to implement code using anonymous inner classes : ```java Runnable runnable = new Runnable() { @Override public void run() { System.out.println("running1 ....."); } }; runnable.run(); ``` Use lambda Expressions implement simpler code : ```java Runnable runnable3 = ()-> System.out.println("running2...."); runnable3.run(); ``` **lambda Representational grammar :** ```java LambdaParameters -> LambdaBody ```  args -> expr perhaps (object ... args)-> { Function interface abstract method implementation logic } 1、() The number of arguments , According to the abstract arguments in the function interface to determine , When there is only one argument ,() It can be omitted 2、 When expr When the logic is very simple ,{} and return It can be omitted ** Case description :** ```java public static void main(String[] args) throws Exception { Callable
c1 = new Callable() { @Override public String call() throws Exception { return "muxiaonong"; } }; System.out.println(c1.call()); Callable
c2 = ()->{return "muxiaonong2";}; System.out.println(c2.call()); // Omit when the logic is simple {} and return Callable
c3 = ()->"muxiaonong3"; System.out.println(c3.call()); } ``` ## Two 、Lambda The characteristics of the expression - Function language programming - Argument types are automatically inferred - Less code , Simplicity ## 3、 ... and 、Lambda Expression case ** List of implementations :** ```java ()->{} ()->{System.out.println(1);} ()->System.out.println(1) ()->{return 100;} ()->100 ()->null (int x)->{return x+1;} (int x)->x+1 (x)->x+1 x->x+1 ``` Case study 1: Thread implementation : ```java public static void main(String[] args) { // Anonymous inner class mode new Thread(new Runnable() { @Override public void run() { System.out.println("runing1.........."); } }); //Lambda The way of expression new Thread(() -> {System.out.println("runing2.....");}).start(); } ``` Case study 2: Collection traversal implementation ```java public static void main(String[] args) { List
list = Arrays.asList("java","python","scala","javascript"); // Common anonymous inner class mode Collections.sort(list, new Comparator
() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }); //Lambda The way Collections.sort(list,(a,b) -> a.length() - b.length()); list.forEach(System.out::println); } ``` ## Four 、Lambda The application scenario of expression Say important things three times :** Wherever there is a functional interface * 3** ** What is a function interface :** ``` There is only one abstract method (Object Except for methods in the class ) The interface of is a function interface ``` ## 5、 ... and 、Lambda Practical application of expression #### 5.1 Parameterless entity simulation ** Simulate the database connection layer :** ```java @FunctionalInterface public interface StudentDao { void insert(Student student); } ``` Entity class ```java /** @Author mxn * @Description Student entity class * @Date 10:19 2020/11/7 * @Param * @return **/ public class Student { } ``` ```java public static void main(String[] args) { StudentDao sd1 = new StudentDao() { @Override public void insert(Student student) { System.out.println(" Insert students 1"); } }; StudentDao sd2 = (student)->{ System.out.println("student: "+student); }; StudentDao sd3 = (Student student)-> System.out.println("student3:"+student); sd1.insert(new Student()); // Output Insert students 1 sd2.insert(new Student());// Output sd3.insert(new Student());// Output } ``` #### 5.2 Parameter entity class simulation Entity class ```java /** @Author mxn * @Description * @Date 10:26 2020/11/7 * @Param * @return **/ public class Teacher { } ``` Interface simulation layer ```java @FunctionalInterface public interface TeacherDao { int get(Teacher teacher); } ``` Implementation layer ```java public static void main(String[] args) { TeacherDao td1 = new TeacherDao() { @Override public int get(Teacher teacher) { return 1; } }; TeacherDao td2 = (teacher)->{return 2;}; TeacherDao td3 = (Teacher teacher)->{return 3;}; TeacherDao td4 = (teacher)->4; TeacherDao td5 = (Teacher teacher)->5; System.out.println(td1.get(new Teacher()));// Output 1 System.out.println(td2.get(new Teacher()));// Output 2 System.out.println(td3.get(new Teacher()));// Output 3 System.out.println(td4.get(new Teacher()));// Output 4 System.out.println(td5.get(new Teacher()));// Output 5 } ``` ## 6、 ... and 、 Function interface ```Supplier:``` Represents an output ```Consumer:``` Represents an input ```BiConsumer:``` Represents two inputs ```Function:``` Represents an input , An output ( General input and output are different types ) ```UnaryOperator:``` Represents an input , An output ( The input and output are of the same type ) ```BiFunction:``` Represents two inputs , An output ( General input and output are different types ) ```BinaryOperator:``` Represents two inputs , An output ( The input and output are of the same type ) ** stay Java Provides a series of function interfaces in , The logic used to accept subsequent inputs , But there are requirements for input and output ** #### 6.1 Supplier: Represents an output ```java Supplier
s1 = ()->{return "muxiaonong";}; Supplier
s2 = ()->"muxiaonong2"; System.out.println(s1.get());// Output muxiaonong System.out.println(s2.get());// Output muxiaonong2 ``` #### 6.2 Consumer: Represents an input ```java Consumer
c11 = (str) -> System.out.println(str); c11.accept("beijing");// Output beijing ``` #### 6.3 BiConsumer: Represents two inputs ```java BiFunction
bf = (a,b)->a.length()+b.length(); System.out.println(bf.apply(" prosperous ", " I'll have chicken tonight "));// Output a string length 8 ``` #### 6.4 Function: Represents an input , An output ```java // Function
To receive the implementation of the following function , There must be an input (String) There's an output (Integer) Function
f1 = (str)->{return str.length();}; System.out.println(f1.apply("abcdefg"));// Output length 7 ``` ## 7、 ... and 、 Method reference - A method reference is an existing method or constructor used to directly access a class or instance item , Method references provide a way to refer to methods without executing them , If the implementation of an abstract method happens to be implemented by calling another method , It is possible to use method references #### 7.1 Classification of method references Type | Grammar | Corresponding lambda The expression -------- | ----- | ----- Static method references | Class name ::staticMethod | (args) -> Class name .staticMethod(args) Method item reference | inst::instMethod| (args) -> inst.instMethod(args) Object method reference | Class name ::instMethod| (inst,args) -> Class name .instMethod(args) Constructor reference | Class name ::new| (args) -> new Class name (args) #### 7.2 Static method references - ** Static method references :** If the implementation of the function interface can happen through ** Call a static method ** To achieve , Then you can use static methods to reference ```java /** * @program: lambda * @ClassName Test2 * @description: * @author: muxiaonong * @create: 2020-10-28 22:15 * @Version 1.0 **/ public class Test2 { // Nonparametric static methods static String put(){ System.out.println("put....."); return "put"; } // Parametric static methods public static void getSize(int size){ System.out.println(size); } // Ginseng Static method with return value public static String toUpperCase(String str){ return str.toUpperCase(); } // Two in , A return value static method public static Integer getLength(String str,String str2){ return str.length()+str2.length(); } public static void main(String[] args) { // Nonparametric static methods - Normal call System.out.println(put());// Output put // Nonparametric static methods - Native call Supplier
s1 = ()-> Test2.put(); System.out.println(s1.get());// Output put // Nonparametric static methods - Static method references Supplier
s2 = Test2::put; System.out.println(s2.get());// Output put // Nonparametric static methods - Inner class calls Supplier
s3 = Fun::hehe; System.out.println(s3.get()); // Output hehe // Parametric static methods - Static method references Consumer
c1 = Test2::getSize; Consumer
c2 = (size)-> Test2.getSize(size); c1.accept(123); c2.accept(111); // Static methods with parameters and return values Function
f1 = (str)->str.toUpperCase(); Function
f2 = (str)-> Test2.toUpperCase(str); Function
f3 = Test2::toUpperCase; Function
f4 = Test2::toUpperCase; System.out.println(f1.apply("abc"));// Output ABC System.out.println(f2.apply("abc"));// Output ABC System.out.println(f3.apply("abc"));// Output ABC System.out.println(f4.apply("abc"));// Output ABC // Two arguments A return value Function interface BiFunction
bf = (a, b)->a.length()+b.length(); BiFunction
bf2 = Test2::getLength; System.out.println(bf2.apply("abc", "def"));// Output 6 System.out.println(bf.apply("abc", "def"));// Output 6 } // Inner class class Fun { public static String hehe(){ return "hehe"; } public static String toUpperCase(String str){ return str.toUpperCase(); } } } ``` #### 7.3 Method item reference - ** Method item reference :** If the implementation of a function interface happens to be implemented by calling the instance method of an instance , Then you can use the example method to reference ```java public class Test3 { // The example item has no parameter method public String put(){ return "put..."; } // Example item has reference method public void getSize(int size){ System.out.println("size:"+size); } // The example item has a return value method public String toUpperCase(String str){ return str.toUpperCase(); } public static void main(String[] args) { // Example item no parameter method returns - Normal call System.out.println(new Test3().put());// Output put... Supplier
s1 = ()->new Test3().put(); Supplier
s2 = ()->{return new Test3().put();}; Supplier
s3 = new Test3()::put; System.out.println(s1.get());// Output put... System.out.println(s2.get());// Output put... System.out.println(s3.get());// Output put... // The only way to build one test3 thing Test3 test = new Test3(); Consumer
c1 = (size)->new Test3().getSize(size); Consumer
c2 = new Test3()::getSize; Consumer
c3 = test::getSize; c1.accept(123);// Output size:123 c2.accept(123);// Output size:123 c3.accept(123);// Output size:123 Function
f1 = (str)->str.toUpperCase(); Function
f2 = (str)->test.toUpperCase(str); Function
f3 = new Test3()::toUpperCase; Function
f4 = test::toUpperCase; System.out.println(f1.apply("abc"));// Output ABC System.out.println(f2.apply("abc"));// Output ABC System.out.println(f3.apply("abc"));// Output ABC System.out.println(f4.apply("abc"));// Output ABC } } ``` #### 7.4 Object method reference - ** Object method reference :** The first argument type of an abstract method happens to be the type of the instance method , The remaining arguments of the abstract method can be used as the arguments of the instance method . If the implementation of the function interface can be implemented by the example method call mentioned above , Then you can use the method ```java /** @Author mxn * @Description //TODO Object method reference * @Date 14:26 2020/11/7 * @Param * @return **/ public class Test4 { public static void main(String[] args) { Consumer
c1 = (too)->new Too().foo(); c1.accept(new Too());// Output foo Consumer
c2 = (Too too) ->new Too2().foo(); c2.accept(new Too());// Output foo---too2 Consumer
c3 = Too::foo; c3.accept(new Too());// Output foo BiConsumer
bc = (too2,str)->new Too2().show(str); BiConsumer
bc2 = Too2::show; bc.accept(new Too2(),"abc"); bc2.accept(new Too2(),"def"); BiFunction
bf1 = (e,s)->new Exec().test(s); bf1.apply(new Exec(),"abc"); BiFunction
bf2 = Exec::test; bf2.apply(new Exec(),"def"); } } class Exec{ public int test(String name){ return 1; } } class Too{ public Integer fun(String s){ return 1; } public void foo(){ System.out.println("foo"); } } class Too2{ public Integer fun(String s){ return 1; } public void foo(){ System.out.println("foo---too2"); } public void show(String str){ System.out.println("show ---too2"+str); } } ``` #### 7.5 Constructor reference - ** Constructor reference :** If the implementation of a function interface happens to be implemented by calling the constructor of a class , Then you can use the constructor to reference ```java /** @Author mxn * @Description //TODO Constructor reference * @Date 14:27 2020/11/7 * @Param * @return **/ public class Test5 { public static void main(String[] args) { Supplier
s1 = ()->new Person(); s1.get();// Output Call parameterless constructors Supplier
s2 = Person::new; s2.get();// Output Call parameterless constructors Supplier
s3 = ArrayList::new; Supplier
s4 = HashSet::new; Supplier
s5 = Thread::new; Supplier
s6 = String::new; Consumer
c1 = (age)->new Account(age); Consumer
c2 = Account::new; c1.accept(123);// Output age Argument construction 123 c2.accept(456);// Output age Argument construction 456 Function
f1 = (str)->new Account(str); Function
f2 = Account::new; f1.apply("abc");// Output str Argument construction abc f2.apply("def");// Output str Argument construction def } } class Account{ public Account(){ System.out.println(" Call the parameterless constructor "); } public Account(int age){ System.out.println("age Argument construction " +age); } public Account(String str){ System.out.println("str Argument construction " +str); } } class Person{ public Person(){ System.out.println(" Call parameterless constructors "); } } ``` ## 8、 ... and 、 Summary - JAVA 8 introduce Lambda Expression is to receive the idea of function language and programming language , Compared with imperative programming , Function language programming emphasizes that function calculation is more important than instruction execution . - lambda Expressions can make code look simple , But to some extent, it increases the readability of the code and the complexity of debugging , So in the use of the team should try to be familiar with the use of , If you want it dry, don't use it , Otherwise, it will be more painful to maintain , That's all for today's little knowledge , If you have any questions, you can leave a message below , everyone