JDK new feature God operation of lambda expression

itread01 2020-11-07 16:46:47
jdk new feature god operation


## 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 ``` ![ Insert picture description here ](https://img-blog.csdnimg.cn/20201107094149930.png#pic_center) 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
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云