JDK新特性-Lambda表达式的神操作

2025-05-29 0 29

JDK新特性-Lambda表达式的神操作

一、Lambda表达式的介绍

  • Lambda表达式是 Java8 中最重要的新功能之一。使用 Lambda 表达式可以替代只有一个抽象函数的接口实现,告别匿名内部类,代码看起来更简洁易懂。Lambda表达式同时还提升了对集合、框架的迭代、遍历、过滤数据的操作。
  • lambda表达式可以替代只有一个抽象函数的接口实现,告别匿名内部类,代码看起来更简洁易懂
  • lambda表达式同时还提升了对集合、框架的迭代、遍历、过滤数据的操作
  • lambda可以极大的减少代码冗余,同时代码的可读性要好过冗长的内部类,匿名类

例如以前我们使用匿名内部类来实现代码:

  1. Runnablerunnable=newRunnable(){
  2. @Override
  3. publicvoidrun(){
  4. System.out.println("running1…..");
  5. }
  6. };
  7. runnable.run();

使用lambda表达式实现更简洁的代码:

  1. Runnablerunnable3=()->System.out.println("running2….");
  2. runnable3.run();

lambda表达式语法:

  1. LambdaParameters->LambdaBody

JDK新特性-Lambda表达式的神操作

在这里插入图片描述

args -> expr或者(object … args)-> {函数式接口抽象方法实现逻辑}

1、()参数的个数,根据函数式接口里面抽象的参数个数来决定,当参数只有一个的时候,()可以省略

2、当expr逻辑非常简单的时候,{}和return可以省略

案例说明:

  1. publicstaticvoidmain(String[]args)throwsException{
  2. Callable<String>c1=newCallable(){
  3. @Override
  4. publicStringcall()throwsException{
  5. return"muxiaonong";
  6. }
  7. };
  8. System.out.println(c1.call());
  9. Callable<String>c2=()->{return"muxiaonong2";};
  10. System.out.println(c2.call());
  11. //逻辑很简单的时候省略{}和return
  12. Callable<String>c3=()->"muxiaonong3";
  13. System.out.println(c3.call());
  14. }

二、Lambda表达式的特点

  • 函数式编程
  • 参数类型自动推断
  • 代码量少,简洁

三、Lambda表达式案例

实现方式列表:

  1. ()->{}
  2. ()->{System.out.println(1);}
  3. ()->System.out.println(1)
  4. ()->{return100;}
  5. ()->100
  6. ()->null
  7. (intx)->{returnx+1;}
  8. (intx)->x+1
  9. (x)->x+1
  10. x->x+1

案例1:线程实现方式:

  1. publicstaticvoidmain(String[]args){
  2. //匿名内部类方式
  3. newThread(newRunnable(){
  4. @Override
  5. publicvoidrun(){
  6. System.out.println("runing1……….");
  7. }
  8. });
  9. //Lambda表达式方式
  10. newThread(()->{System.out.println("runing2…..");}).start();
  11. }

案例2:集合遍历实现方式

  1. publicstaticvoidmain(String[]args){
  2. List<String>list=Arrays.asList("java","python","scala","javascript");
  3. //普通匿名内部类方式
  4. Collections.sort(list,newComparator<String>(){
  5. @Override
  6. publicintcompare(Stringo1,Stringo2){
  7. returno1.length()-o2.length();
  8. }
  9. });
  10. //Lambda方式
  11. Collections.sort(list,(a,b)->a.length()-b.length());
  12. list.forEach(System.out::println);
  13. }

四、Lambda表达式的应用场景

重要的事情说三遍:任何有函数式接口的地方 * 3

什么是函数式接口: 只有一个抽象方法(Object类中的方法除外)的接口是函数式接口

五、Lambda表达式实际应用

5.1 无参实体类模拟

模拟数据库连接层:

  1. @FunctionalInterface
  2. publicinterfaceStudentDao{
  3. voidinsert(Studentstudent);
  4. }

实体类

  1. /**@Authormxn
  2. *@Description学生实体类
  3. *@Date10:192020/11/7
  4. *@Param
  5. *@return
  6. **/
  7. publicclassStudent{
  8. }
  9. publicstaticvoidmain(String[]args){
  10. StudentDaosd1=newStudentDao(){
  11. @Override
  12. publicvoidinsert(Studentstudent){
  13. System.out.println("插入学生1");
  14. }
  15. };
  16. StudentDaosd2=(student)->{
  17. System.out.println("student:"+student);
  18. };
  19. StudentDaosd3=(Studentstudent)->System.out.println("student3:"+student);
  20. sd1.insert(newStudent());//输出插入学生1
  21. sd2.insert(newStudent());//输出
  22. sd3.insert(newStudent());//输出
  23. }

5.2 有参实体类模拟

实体类

  1. /**@Authormxn
  2. *@Description
  3. *@Date10:262020/11/7
  4. *@Param
  5. *@return
  6. **/
  7. publicclassTeacher{
  8. }

接口模拟层

  1. @FunctionalInterface
  2. publicinterfaceTeacherDao{
  3. intget(Teacherteacher);
  4. }

实现层

  1. publicstaticvoidmain(String[]args){
  2. TeacherDaotd1=newTeacherDao(){
  3. @Override
  4. publicintget(Teacherteacher){
  5. return1;
  6. }
  7. };
  8. TeacherDaotd2=(teacher)->{return2;};
  9. TeacherDaotd3=(Teacherteacher)->{return3;};
  10. TeacherDaotd4=(teacher)->4;
  11. TeacherDaotd5=(Teacherteacher)->5;
  12. System.out.println(td1.get(newTeacher()));//输出1
  13. System.out.println(td2.get(newTeacher()));//输出2
  14. System.out.println(td3.get(newTeacher()));//输出3
  15. System.out.println(td4.get(newTeacher()));//输出4
  16. System.out.println(td5.get(newTeacher()));//输出5
  17. }

六、函数式接口

Supplier:代表一个输出

Consumer:代表一个输入

BiConsumer:代表两个输入

Function:代表一个输入,一个输出(一般输入和输出是不同类型的)

UnaryOperator:代表一个输入,一个输出(输入和输出是相同类型的)

BiFunction:代表两个输入,一个输出(一般输入和输出是不同类型的)

BinaryOperator:代表两个输入,一个输出(输入和输出是相同类型的)

在Java中提供了一系列的函数式接口,用来接受后续传入的逻辑,但是对输入和输出有要求

6.1 Supplier:代表一个输出

  1. Supplier<String>s1=()->{return"muxiaonong";};
  2. Supplier<String>s2=()->"muxiaonong2";
  3. System.out.println(s1.get());//输出muxiaonong
  4. System.out.println(s2.get());//输出muxiaonong2

6.2 Consumer:代表一个输入

  1. Consumer<String>c11=(str)->System.out.println(str);
  2. c11.accept("beijing");//输出beijing

6.3 BiConsumer:代表两个输入

  1. BiFunction<String,String,Integer>bf=(a,b)->a.length()+b.length();
  2. System.out.println(bf.apply("大吉大利","今晚吃鸡"));//输出一个字符串长度8

6.4 Function:代表一个输入,一个输出

  1. //Function<String,Integer>用来接收后面的函数的实现,规定必须有一个输入(String)有一个输出(Integer)
  2. Function<String,Integer>f1=(str)->{returnstr.length();};
  3. System.out.println(f1.apply("abcdefg"));//输出长度7

七、方法的引用

方法引用是用来直接访问类或者实例的已经存在的方法或者构造方法,方法引用提供了一种引用而不执行方法的方式,如果抽象方法的实现恰好可以使用调用另外一个方法来实现,就有可能可以使用方法引用

7.1 方法引用的分类

JDK新特性-Lambda表达式的神操作

7.2 静态方法引用

静态方法引用: 如果函数式接口的实现恰好可以通过 调用一个静态方法 来实现,那么就可以使用静态方法引用

  1. /**
  2. *@program:lambda
  3. *@ClassNameTest2
  4. *@description:
  5. *@author:muxiaonong
  6. *@create:2020-10-2822:15
  7. *@Version1.0
  8. **/
  9. publicclassTest2{
  10. //无参静态方法
  11. staticStringput(){
  12. System.out.println("put…..");
  13. return"put";
  14. }
  15. //有参静态方法
  16. publicstaticvoidgetSize(intsize){
  17. System.out.println(size);
  18. }
  19. //有参有返回值静态方法
  20. publicstaticStringtoUpperCase(Stringstr){
  21. returnstr.toUpperCase();
  22. }
  23. //两个入参,一个返回值静态方法
  24. publicstaticIntegergetLength(Stringstr,Stringstr2){
  25. returnstr.length()+str2.length();
  26. }
  27. publicstaticvoidmain(String[]args){
  28. //无参静态方法-普通调用
  29. System.out.println(put());//输出put
  30. //无参静态方法-原生调用
  31. Supplier<String>s1=()->Test2.put();
  32. System.out.println(s1.get());//输出put
  33. //无参静态方法-静态方法引用
  34. Supplier<String>s2=Test2::put;
  35. System.out.println(s2.get());//输出put
  36. //无参静态方法-内部类调用
  37. Supplier<String>s3=Fun::hehe;
  38. System.out.println(s3.get());//输出hehe
  39. //有参静态方法-静态方法引用
  40. Consumer<Integer>c1=Test2::getSize;
  41. Consumer<Integer>c2=(size)->Test2.getSize(size);
  42. c1.accept(123);
  43. c2.accept(111);
  44. //有参有返回值静态方法
  45. Function<String,String>f1=(str)->str.toUpperCase();
  46. Function<String,String>f2=(str)->Test2.toUpperCase(str);
  47. Function<String,String>f3=Test2::toUpperCase;
  48. Function<String,String>f4=Test2::toUpperCase;
  49. System.out.println(f1.apply("abc"));//输出ABC
  50. System.out.println(f2.apply("abc"));//输出ABC
  51. System.out.println(f3.apply("abc"));//输出ABC
  52. System.out.println(f4.apply("abc"));//输出ABC
  53. //两个参数一个返回值函数式接口
  54. BiFunction<String,String,Integer>bf=(a,b)->a.length()+b.length();
  55. BiFunction<String,String,Integer>bf2=Test2::getLength;
  56. System.out.println(bf2.apply("abc","def"));//输出6
  57. System.out.println(bf.apply("abc","def"));//输出6
  58. }
  59. //内部类
  60. classFun{
  61. publicstaticStringhehe(){
  62. return"hehe";
  63. }
  64. publicstaticStringtoUpperCase(Stringstr){
  65. returnstr.toUpperCase();
  66. }
  67. }
  68. }

7.3 实例方法引用

实例方法引用: 如果函数式接口的实现恰好可以通过调用一个实例的实例方法来实现,那么就可以使用实例方法引用

  1. publicclassTest3{
  2. //实例无参方法
  3. publicStringput(){
  4. return"put…";
  5. }
  6. //实例有参方法
  7. publicvoidgetSize(intsize){
  8. System.out.println("size:"+size);
  9. }
  10. //实例有参有返回值方法
  11. publicStringtoUpperCase(Stringstr){
  12. returnstr.toUpperCase();
  13. }
  14. publicstaticvoidmain(String[]args){
  15. //实例无参方法返回-普通调用
  16. System.out.println(newTest3().put());//输出put…
  17. Supplier<String>s1=()->newTest3().put();
  18. Supplier<String>s2=()->{returnnewTest3().put();};
  19. Supplier<String>s3=newTest3()::put;
  20. System.out.println(s1.get());//输出put…
  21. System.out.println(s2.get());//输出put…
  22. System.out.println(s3.get());//输出put…
  23. //唯一的创建一个test3对象
  24. Test3test=newTest3();
  25. Consumer<Integer>c1=(size)->newTest3().getSize(size);
  26. Consumer<Integer>c2=newTest3()::getSize;
  27. Consumer<Integer>c3=test::getSize;
  28. c1.accept(123);//输出size:123
  29. c2.accept(123);//输出size:123
  30. c3.accept(123);//输出size:123
  31. Function<String,String>f1=(str)->str.toUpperCase();
  32. Function<String,String>f2=(str)->test.toUpperCase(str);
  33. Function<String,String>f3=newTest3()::toUpperCase;
  34. Function<String,String>f4=test::toUpperCase;
  35. System.out.println(f1.apply("abc"));//输出ABC
  36. System.out.println(f2.apply("abc"));//输出ABC
  37. System.out.println(f3.apply("abc"));//输出ABC
  38. System.out.println(f4.apply("abc"));//输出ABC
  39. }
  40. }

7.4 对象方法引用

对象方法引用: 抽象方法的第一个参数类型刚好是实例方法的类型,抽象方法剩余的参数恰好可以当做实例方法的参数。如果函数式接口的实现能由上面说的实例方法调用来实现的话,那么就可以使用对象方法引用

  1. /**@Authormxn
  2. *@Description//TODO对象方法引用
  3. *@Date14:262020/11/7
  4. *@Param
  5. *@return
  6. **/
  7. publicclassTest4{
  8. publicstaticvoidmain(String[]args){
  9. Consumer<Too>c1=(too)->newToo().foo();
  10. c1.accept(newToo());//输出foo
  11. Consumer<Too>c2=(Tootoo)->newToo2().foo();
  12. c2.accept(newToo());//输出foo—too2
  13. Consumer<Too>c3=Too::foo;
  14. c3.accept(newToo());//输出foo
  15. BiConsumer<Too2,String>bc=(too2,str)->newToo2().show(str);
  16. BiConsumer<Too2,String>bc2=Too2::show;
  17. bc.accept(newToo2(),"abc");
  18. bc2.accept(newToo2(),"def");
  19. BiFunction<Exec,String,Integer>bf1=(e,s)->newExec().test(s);
  20. bf1.apply(newExec(),"abc");
  21. BiFunction<Exec,String,Integer>bf2=Exec::test;
  22. bf2.apply(newExec(),"def");
  23. }
  24. }
  25. classExec{
  26. publicinttest(Stringname){
  27. return1;
  28. }
  29. }
  30. classToo{
  31. publicIntegerfun(Strings){
  32. return1;
  33. }
  34. publicvoidfoo(){
  35. System.out.println("foo");
  36. }
  37. }
  38. classToo2{
  39. publicIntegerfun(Strings){
  40. return1;
  41. }
  42. publicvoidfoo(){
  43. System.out.println("foo—too2");
  44. }
  45. publicvoidshow(Stringstr){
  46. System.out.println("show—too2"+str);
  47. }
  48. }

7.5 构造方法引用

构造方法引用: 如果函数式接口的实现恰好可以通过调用一个类的构造方法来实现,那么就可以使用构造方法引用

  1. /**@Authormxn
  2. *@Description//TODO构造方法引用
  3. *@Date14:272020/11/7
  4. *@Param
  5. *@return
  6. **/
  7. publicclassTest5{
  8. publicstaticvoidmain(String[]args){
  9. Supplier<Person>s1=()->newPerson();
  10. s1.get();//输出调用无参的构造方法
  11. Supplier<Person>s2=Person::new;
  12. s2.get();//输出调用无参的构造方法
  13. Supplier<List>s3=ArrayList::new;
  14. Supplier<Set>s4=HashSet::new;
  15. Supplier<Thread>s5=Thread::new;
  16. Supplier<String>s6=String::new;
  17. Consumer<Integer>c1=(age)->newAccount(age);
  18. Consumer<Integer>c2=Account::new;
  19. c1.accept(123);//输出age参数构造123
  20. c2.accept(456);//输出age参数构造456
  21. Function<String,Account>f1=(str)->newAccount(str);
  22. Function<String,Account>f2=Account::new;
  23. f1.apply("abc");//输出str参数构造abc
  24. f2.apply("def");//输出str参数构造def
  25. }
  26. }
  27. classAccount{
  28. publicAccount(){
  29. System.out.println("调用无参构造方法");
  30. }
  31. publicAccount(intage){
  32. System.out.println("age参数构造"+age);
  33. }
  34. publicAccount(Stringstr){
  35. System.out.println("str参数构造"+str);
  36. }
  37. }
  38. classPerson{
  39. publicPerson(){
  40. System.out.println("调用无参的构造方法");
  41. }
  42. }

八、小结

  • Java8 引入 Lambda表达式是接收了函数式编程语言的思想,和指令式编程相比,函数式编程强调函数的计算比指令的执行重要。引入 Lambda表达式是接收了函数式编程语言的思想,和指令式编程相比,函数式编程强调函数的计算比指令的执行重要。引入 Lambda表达式是接收了函数式编程语言的思想,和指令式编程相比,函数式编程强调函数的计算比指令的执行重要。
  • lambda表达式可以使代码看起来简洁,但一定程度上增加了代码的可读性以及调试的复杂性,所以在使用时应尽量是团队都熟悉使用,要么干脆就别用,不然维护起来是件较痛苦的事,今天的小知识就到这里了,有问题的小伙伴可以在下方进行留言,大家加油!

原文地址:https://mp.weixin.qq.com/s/9tWEoCqlEoHkKzAgMFAzzA

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 JDK新特性-Lambda表达式的神操作 https://www.kuaiidc.com/111983.html

相关文章

发表评论
暂无评论