1. //函数式接口:只有一个抽象方法的接口称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
  2. @FunctionalInterface
  3. public interface MyFun {
  4. public Integer getValue(Integer num);
  5. }
  1. import java.util.ArrayList;
  2. import java.util.Comparator;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.function.Consumer;
  7.  
  8. import org.junit.Test;
  9.  
  10. /*
  11. * 一、Lambda 表达式的基础语法:Java8中引入了一个新的操作符 "->" 该操作符称为箭头操作符或 Lambda 操作符
  12. * 箭头操作符将 Lambda 表达式拆分成两部分:
  13. *
  14. * 左侧:Lambda 表达式的参数列表
  15. * 右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体
  16. *
  17. * 语法格式一:无参数,无返回值
  18. * () -> System.out.println("Hello Lambda!");
  19. *
  20. * 语法格式二:有一个参数,并且无返回值
  21. * (x) -> System.out.println(x)
  22. *
  23. * 语法格式三:若只有一个参数,小括号可以省略不写
  24. * x -> System.out.println(x)
  25. *
  26. * 语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
  27. * Comparator<Integer> com = (x, y) -> {
  28. * System.out.println("函数式接口");
  29. * return Integer.compare(x, y);
  30. * };
  31. *
  32. * 语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写
  33. * Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
  34. *
  35. * 语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
  36. * (Integer x, Integer y) -> Integer.compare(x, y);
  37. *
  38. * 上联:左右遇一括号省
  39. * 下联:左侧推断类型省
  40. * 横批:能省则省
  41. *
  42. * 二、Lambda 表达式需要“函数式接口”的支持
  43. * 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
  44. * 可以检查是否是函数式接口
  45. */
  46. public class TestLambda2 {
  47.  
  48. @Test
  49. public void test1(){
  50. int num = 0;//jdk 1.7 前,必须是 final
  51.  
  52. Runnable r = new Runnable() {
  53. @Override
  54. public void run() {
  55. System.out.println("Hello World!" + num);
  56. }
  57. };
  58.  
  59. r.run();
  60.  
  61. System.out.println("-------------------------------");
  62.  
  63. Runnable r1 = () -> System.out.println("Hello Lambda!");
  64. r1.run();
  65. }
  66.  
  67. @Test
  68. public void test2(){
  69. Consumer<String> con = x -> System.out.println(x);
  70. con.accept("我大尚硅谷威武!");
  71. }
  72.  
  73. @Test
  74. public void test3(){
  75. Comparator<Integer> com = (x, y) -> {
  76. System.out.println("函数式接口");
  77. return Integer.compare(x, y);
  78. };
  79. }
  80.  
  81. @Test
  82. public void test4(){
  83. Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
  84. }
  85. /**自动推断类型*/
  86. @Test
  87. public void test5(){
          String[] aaa = {"abc","def","ghi"}; //后面的值也没有写类型,根据前面自动推断出来的
  88. // String[] strs;
  89. // strs = {"aaa", "bbb", "ccc"}; 拆开写无法推断出类型,会报错
  90.  
  91. List<String> list = new ArrayList<>(); //java7 后面不用写类型了,因为可以根据前面推断出来,只写一个<> 即可
  92.  
  93. show(new HashMap<>());        //在Java8中,show()方法中创建的Map用泛型即可,因为可以根据方法类型自动推断出
  94. }
  95.  
  96. public void show(Map<String, Integer> map){ //方法定义中已经指定了类型
  97.  
  98. }
  99.  
  100. //需求:对一个数进行运算
  101. @Test
  102. public void test6(){
  103. Integer num = operation(100, (x) -> x * x);
  104. System.out.println(num);
  105.  
  106. System.out.println(operation(200, (y) -> y + 200));
  107. }
  108.  
  109. public Integer operation(Integer num, MyFun mf){
  110. return mf.getValue(num);
  111. }
  112. }

小例子:

  1. public class Test {
  2.  
  3. /**
  4. * 1.调用Collection.sort()方法,通过定制排序比较2个Employee(先按年龄比,年龄一样按姓名比),使用lambda表达式传递参数
  5. */
  6.  
  7. public static void main(String[] args) {
  8. List<Employee> emps = Arrays.asList(
  9. new Employee(101, "张三", 18, 9999.99),
  10. new Employee(102, "李四", 59, 6666.66),
  11. new Employee(103, "王五", 28, 3333.33),
  12. new Employee(104, "赵六", 8, 7777.77),
  13. new Employee(105, "田七", 38, 5555.55)
  14. );
  15.  
  16. Collections.sort(emps,(x1,x2) -> {
  17. if(x1.getAge() == x2.getAge())
  18. return x1.getName().compareTo(x2.getName());
  19. else
  20. return -Integer.compare(x1.getAge(),x2.getAge());
  21. });
  22. for (Employee emp : emps)
  23. System.out.println(emp);
  24. }
  25. }
  1. /**
  2. * 1.声明函数式接口,接口中声明抽象方法,public String getValue(String str);
  3. * 2.声明测试类,类中编写方法使用接口作为参数,
  4. * 1)讲一个字符串转换为大写
  5. * 2)去掉首位空格
  6. * 3)截取字符串
  7. */
  8.  
  9. @FunctionalInterface
  10. public interface MyFunction {
  11.  
  12. public String getValue(String str);
  13. }
  14.  
  15. public class Test {
  16. public static void main(String[] args) {
  17.  
  18. System.out.println(handleStr("hello world", x -> x.toUpperCase()));
  19. System.out.println(handleStr("\t\t\t hello world", x -> x.trim()));
  20. System.out.println(handleStr("hello world", x -> x.substring(0,2)));
  21.  
  22. }
  23.  
  24. public static String handleStr(String str, MyFunction mf) {
  25. return mf.getValue(str);
  26. }
  27. }
  1. /**
  2. * 1.声明一个带2个泛型的函数式接口,泛型类型为<T,R> T为参数,R为返回值
  3. * 2.接口中声明对应抽象方法
  4. * 3.在测试类中声明方法,使用接口做为参数,计算2个Long类型参数的和
  5. * 4.再计算2个Long类型参数的乘积
  6. */
  7.  
  8. @FunctionalInterface
  9. public interface MyFunction2<T,R> {
  10. R getValue(T t1, T t2);
  11. }
  12.  
  13. public class Test {
  14.  
  15. public static void main(String[] args) {
  16. System.out.println(handleLong(100L,200L,(l1,l2) -> l1 + l2));
  17. System.out.println(handleLong(100L,200L,(l1,l2) -> l1 * l2));
  18. }
  19.  
  20. public static Long handleLong(Long l1,Long l2, MyFunction2<Long,Long> mf) {
  21. return mf.getValue(l1,l2);
  22. }

JDK8新特性02 Lambda表达式02_Lambda语法规则的更多相关文章

  1. 【Java8新特性】Lambda表达式基础语法,都在这儿了!!

    写在前面 前面积极响应读者的需求,写了两篇Java新特性的文章.有小伙伴留言说:感觉Lambda表达式很强大啊!一行代码就能够搞定那么多功能!我想学习下Lambda表达式的语法,可以吗?我的回答是:没 ...

  2. JDK8新特性:Lambda表达式

    Lambda表达式,案例一:new Thread(() -> System.out.println("thread")); Lambda表达式,案例二:由参数/箭头和主体组成 ...

  3. JDK8新特性(一) Lambda表达式及相关特性

    函数式接口 函数式接口是1.8中的新特性,他不属于新语法,更像是一种规范 面向对象接口复习 在这里先回顾一下面向对象的接口,创建接口的关键字为interface,这里创建一个日志接口: public ...

  4. JDK8新特性之Lambda表达式

    Lambda表达式主要是替换了原有匿名内部类的写法,也就是简化了匿名内部类的写法.lambda语法结构: (参数1,参数2...)->{重写方法的内容,不定义方法名} 先看一个使用匿名内部类定义 ...

  5. JDK8新特性01 Lambda表达式01_设计的由来

    1.java bean public class Employee { private int id; private String name; private int age; private do ...

  6. jdk8新特性--使用lambda表达式的延迟执行特性优化性能

    使用lambda表达式的延迟加载特性对代码进行优化:

  7. JDK8新特性03 Lambda表达式03_Java8 内置的四大核心函数式接口

    import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.functio ...

  8. java8新特性: lambda表达式:直接获得某个list/array/对象里面的字段集合

    java8新特性: lambda表达式:直接获得某个list/array/对象里面的字段集合 比如,我有一张表: entity Category.java service CategoryServic ...

  9. Java8 新特性学习 Lambda表达式 和 Stream 用法案例

    Java8 新特性学习 Lambda表达式 和 Stream 用法案例 学习参考文章: https://www.cnblogs.com/coprince/p/8692972.html 1.使用lamb ...

随机推荐

  1. CSS垂直翻转与水平翻转

    /*水平翻转*/ .flipx { -moz-transform:scaleX(-1); -webkit-transform:scaleX(-1); -o-transform:scaleX(-1); ...

  2. hdu 1686 Oulipo (kmp)

    Problem Description The French author Georges Perec (1936–1982) once wrote a book, La disparition, w ...

  3. 网页发起qq临时会话

    qq官方:http://shang.qq.com/v3/widget.html

  4. 纪中2018暑假培训day1提高b组改题记录

    收到意见,认为每天的程序和随笔放在一起写的博客太长了,于是分开整理 day1 模拟赛,看了看提高a组t1的样例就不太想写,于是转而写b组 t1: Description 给定一个n个点m条边的有向图, ...

  5. PHP中empty,is_null,isset的区别

    有时候分不清这几个的区别,特此记录,以备不时之需 isset 判断变量是否已存在 empty 判断变量是否为空或为0 is_null 判断变量是否为NULL 变量 empty is_null isse ...

  6. JQERY EasyUI Tabs 选项卡 自适应浏览器宽度高度 解决方案

    <script type="text/javascript"> $(window).resize(function () { $('#tt').tabs({ width ...

  7. php项目核心业务(增、删、改、查)(第三篇)

    对增删改查数据库的封装 //php对数据库的封装 //Mysql_fetach($sql)函数查询所有的 function Mysql_fetach($sql){ $conn=mysqli_conne ...

  8. 字符输入流 FileReader

    package cn.lideng.demo3; import java.io.FileNotFoundException; import java.io.FileReader; public cla ...

  9. Linux 普通用户免密码切换到root用户

    Linux 普通用户免密码切换到root用户 # 添加用户 useradd user_name # 修改密码 echo "user_name@pwd" | passwd --std ...

  10. bzoj1009 KMP+矩阵dp

    https://www.lydsy.com/JudgeOnline/problem.php?id=1009 阿申准备报名参加GT考试,准考证号为N位数X1X2....Xn(<=Xi<=), ...