[编程代码] Java8新特性:函数式接口,方法与构造器引用

4220 0
黑夜隐士 2021-12-13 08:11:57 | 显示全部楼层 |阅读模式

前言

★ 这里是小冷的博客
优质技术好文见专栏
个人公众号,分享一些技术上的文章,以及遇到的坑
当前系列:Java8 新特性 系列
源代码 git 仓库 代码Git 仓库地址

Java8 新特性

函数式接口(Functional)

通过上面的 Lambda表达式的学习,我们认识了 新的语法,支持这种语法的接口

  • 只包含一个抽象方法的接口,称为函数式接口
  • 你只可以通过 Lambda表达式,来创建该接口的对象,(Lambda表达式抛出一个抛出一个检查异常(即,运行时异常),这个衣长需要在目标接口的抽象方法上进行声明)
  • 我们可以在接口上使用@FunctionalInterface注解,这样做可以检查这个接口是不是函数式接口,同时javadoc也会包含一条声明说明这个接口是一个函数式接口,
  • java.util.funcion包下定义了Java8丰富的函数式接口

Lambda的表达式本质其实就是函数式接口的实例

什么是函数式接口呢?

Runnable接口就是一个很典型的函数式接口

  1. @FunctionalInterface
  2. public interface Runnable {
  3. public abstract void run();
  4. }
复制代码

这里我们自己定一个

  1. @FunctionalInterface
  2. public interface MyinterFace {
  3. void method1();
  4. }
复制代码

Java内置四大核心函数式接口

函数式接口参数类型返回类型用途
Consumer 消费型接口Tvoid对类型为t的对象应用操作,包含方法void accept(T,t)
Supperlier供给型接口T返回类型为T的对象,包含方法 T get()
FunctionTR对类型为T的对象应用操作,并返回结果,结果是R类型的对象,包含方法 R apply(T t)
PredicateTboolean确定类型为T的对象是否满足某个约束,并返回boolean值,包含方法 boolean test(T t)

理论+实践

我们以 Consumer 与 Predicate举例子

  1. /**
  2. * @author : <h2>冷环渊</h2>
  3. * @date : 2021/12/11
  4. * @context: <h4>
  5. * 消费型接口 Consumer<T> Accept(T t)
  6. * 供给型接口 Supplier<T> T get()
  7. * 函数式接口 Function<T> R apply(T t)
  8. * 断定型接口 Predicate<T> boolean test(T t)
  9. * </h4>
  10. */
  11. public class LambdaTest2 {
  12. /**
  13. * @author 冷环渊 Doomwatcher
  14. * @context: Consumer<T> 使用
  15. * @date: 2021/12/11 14:37
  16. * @param
  17. * @return: void
  18. */
  19. @Test
  20. public void Test1() {
  21. happyTime(500, new Consumer<Double>() {
  22. @Override
  23. public void accept(Double aDouble) {
  24. System.out.println("天上人间的水今天很贵:" + aDouble);
  25. }
  26. });
  27. System.out.println("****************************");
  28. happyTime(400, money -> System.out.println("学习太累了,去天上人间买了瓶矿泉水,价格为:" + money));
  29. }
  30. /**
  31. * @author: 冷环渊 Doomwatcher
  32. * @context:
  33. * @date: 2021/12/11 14:33
  34. * @param money
  35. * @param con
  36. * @return void
  37. */
  38. public void happyTime(double money, Consumer<Double> con) {
  39. con.accept(money);
  40. }
  41. /**
  42. * @author 冷环渊 Doomwatcher
  43. * @context: 断言 Predicate 的使用
  44. * @date: 2021/12/11 14:39
  45. * @param
  46. * @return: void
  47. */
  48. @Test
  49. public void Test2() {
  50. //传统写法
  51. List<String> filterList = Arrays.asList("北京", "天津", "南京", "东京", "江南");
  52. List<String> filterStr = filterString(filterList, new Predicate<String>() {
  53. @Override
  54. public boolean test(String s) {
  55. return s.contains("京");
  56. }
  57. });
  58. System.out.println(filterStr);
  59. System.out.println("*******************************");
  60. // Lambda表达式 写法
  61. List<String> filterList1 = Arrays.asList("北京", "天津", "南京", "东京", "江南");
  62. List<String> filterStr1 = filterString(filterList1, s -> s.contains("京"));
  63. System.out.println(filterStr1);
  64. }
  65. /**
  66. * @author 冷环渊 Doomwatcher
  67. * @context:
  68. * @date: 2021/12/11 14:49
  69. * @param list
  70. * @param pre
  71. * @return: java.util.List<java.lang.String>
  72. */
  73. public List<String> filterString(List<String> list, Predicate<String> pre) {
  74. ArrayList<String> filterlist = new ArrayList<>();
  75. for (String s : list) {
  76. if (pre.test(s)) {
  77. filterlist.add(s);
  78. }
  79. }
  80. return filterlist;
  81. }
  82. }
复制代码

方法引用与构造器引用

方法引用

  • 当前要传递给 Lambda体的操作,已经有了实现的方法了,可以使用方法引用
  • 方法引用可以看做是Lambda表达式的深层次表达,换句话说,方法引用就是Lambda表达式,只不过和之前我们自己编写不同,这里通过方法的名字来指向一个方法,可以认为是Lambda表达式的一种语法糖
  • 要求:实现接口的抽象方法的参数列表和返回值类型。必须与方法引用的方法的参数列表和返回值保持一致
  • 格式:使用操作符“::”将类或者对象与方法名字分开来
  • 如下是三种主要的使用情况
    • 对象::实例方法名
    • 类::静态方法名
    • 类::实例方法名

coding

准备两个类 一个是list集合,一个是对象

Employee get/set 和 tostring 为防止无用篇幅过长,这里我们简写只看一下对象属性即可

  1. package Lambda.MethodReferences;
  2. /**
  3. *
  4. * @author : <h2>冷环渊</h2>
  5. * @date : 2021/12/11
  6. * @context:<h4>提供用于测试的对象</h4>
  7. */
  8. public class Employee {
  9. private int id;
  10. private String name;
  11. private int age;
  12. private double salary;
  13. \
  14. }
复制代码

EmployeeData

  1. package Lambda.MethodReferences;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. *
  6. * @author : <h2>冷环渊</h2>
  7. * @date : 2021/12/11
  8. * @context:<h4>提供用于测试的数据</h4>
  9. */
  10. public class EmployeeData {
  11. public static List<Employee> getEmployees() {
  12. List<Employee> list = new ArrayList<>();
  13. list.add(new Employee(1001, "马化腾", 34, 6000.38));
  14. list.add(new Employee(1002, "马云", 12, 9876.12));
  15. list.add(new Employee(1003, "刘强东", 33, 3000.82));
  16. list.add(new Employee(1004, "雷军", 26, 7657.37));
  17. list.add(new Employee(1005, "李彦宏", 65, 5555.32));
  18. list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
  19. list.add(new Employee(1007, "任正非", 26, 4333.32));
  20. list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
  21. return list;
  22. }
  23. }
复制代码

方法引用 test

  1. /**
  2. * @author : <h2>冷环渊</h2>
  3. * @date : 2021/12/11
  4. * @context:<h4>
  5. * 方法引用的使用
  6. *
  7. * 1.使用情境:当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
  8. * 2.方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以
  9. * 方法引用,也是函数式接口的实例。
  10. * 3. 使用格式: 类(或对象) :: 方法名
  11. * 4. 具体分为如下的三种情况:
  12. * 情况1 对象 :: 非静态方法
  13. * 情况2 类 :: 静态方法
  14. * 情况3 类 :: 非静态方法
  15. * 5. 方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的
  16. * 形参列表和返回值类型相同!(针对于情况1和情况2)
  17. *
  18. * </h4>
  19. *
  20. */
  21. public class MethodRefTest {
  22. // 情况一:对象 :: 实例方法
  23. //Consumer中的void accept(T t)
  24. //PrintStream中的void println(T t)
  25. @Test
  26. public void test1() {
  27. Consumer<String> con1 = str -> System.out.println(str);
  28. con1.accept("北京");
  29. System.out.println("*******************");
  30. PrintStream ps = System.out;
  31. Consumer<String> con2 = ps::println;
  32. con2.accept("beijing");
  33. }
  34. //Supplier中的T get()
  35. //Employee中的String getName()
  36. @Test
  37. public void test2() {
  38. Employee emp = new Employee(1001, "Tom", 23, 5600);
  39. Supplier<String> sup1 = () -> emp.getName();
  40. System.out.println(sup1.get());
  41. System.out.println("*******************");
  42. Supplier<String> sup2 = emp::getName;
  43. System.out.println(sup2.get());
  44. }
  45. // 情况二:类 :: 静态方法
  46. //Comparator中的int compare(T t1,T t2)
  47. //Integer中的int compare(T t1,T t2)
  48. @Test
  49. public void test3() {
  50. Comparator<Integer> com1 = (t1, t2) -> Integer.compare(t1, t2);
  51. System.out.println(com1.compare(12, 21));
  52. System.out.println("*******************");
  53. Comparator<Integer> com2 = Integer::compare;
  54. System.out.println(com2.compare(12, 3));
  55. }
  56. //Function中的R apply(T t)
  57. //Math中的Long round(Double d)
  58. @Test
  59. public void test4() {
  60. Function<Double, Long> func = new Function<Double, Long>() {
  61. @Override
  62. public Long apply(Double d) {
  63. return Math.round(d);
  64. }
  65. };
  66. System.out.println("*******************");
  67. Function<Double, Long> fuc1 = d -> Math.round(d);
  68. System.out.println(func1.apply(12.3));
  69. System.out.println("*******************");
  70. Function<Double, Long> func2 = Math::round;
  71. System.out.println(func2.apply(12.6));
  72. }
  73. // 情况三:类 :: 实例方法 (有难度)
  74. // Comparator中的int comapre(T t1,T t2)
  75. // String中的int t1.compareTo(t2)
  76. @Test
  77. public void test5() {
  78. Comparator<String> com1 = (s1, s2) -> s1.compareTo(s2);
  79. System.out.println(com1.compare("abc", "abd"));
  80. System.out.println("*******************");
  81. Comparator<String> com2 = String::compareTo;
  82. System.out.println(com2.compare("abd", "abm"));
  83. }
  84. //BiPredicate中的boolean test(T t1, T t2);
  85. //String中的boolean t1.equals(t2)
  86. @Test
  87. public void test6() {
  88. BiPredicate<String, String> pre1 = (s1, s2) -> s1.equals(s2);
  89. System.out.println(pre1.test("abc", "abc"));
  90. System.out.println("*******************");
  91. BiPredicate<String, String> pre2 = String::equals;
  92. System.out.println(pre2.test("abc", "abd"));
  93. }
  94. // Function中的R apply(T t)
  95. // Employee中的String getName();
  96. @Test
  97. public void test7() {
  98. Employee employee = new Employee(1001, "Jerry", 23, 6000);
  99. Function<Employee, String> func1 = e -> e.getName();
  100. System.out.println(func1.apply(employee));
  101. System.out.println("*******************");
  102. Function<Employee, String> func2 = Employee::getName;
  103. System.out.println(func2.apply(employee));
  104. }
  105. }
复制代码

构造方法引用

通过 简化 的方式,来调用不同的构造器

一、构造器引用

  • 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
  • 抽象方法的返回值类型即为构造器所属的类的类型

二、数组引用

  • 大家可以把数组看做是一个特殊的类,则写法与构造器引用一致。
  1. /**
  2. *
  3. * @author : <h2>冷环渊</h2>
  4. * @date : 2021/12/11
  5. * @context:<h4>
  6. *
  7. * 一、构造器引用
  8. * 和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
  9. * 抽象方法的返回值类型即为构造器所属的类的类型
  10. *
  11. * 二、数组引用
  12. * 大家可以把数组看做是一个特殊的类,则写法与构造器引用一致。
  13. * </h4>
  14. */
  15. public class ConstructorRefTest {
  16. //构造器引用
  17. //Supplier中的T get()
  18. //Employee的空参构造器:Employee()
  19. @Test
  20. public void test1() {
  21. Supplier<Employee> sup = new Supplier<Employee>() {
  22. @Override
  23. public Employee get() {
  24. return new Employee();
  25. }
  26. };
  27. System.out.println("*******************");
  28. Supplier<Employee> sup1 = () -> new Employee();
  29. System.out.println(sup1.get());
  30. System.out.println("*******************");
  31. Supplier<Employee> sup2 = Employee::new;
  32. System.out.println(sup2.get());
  33. }
  34. //Function中的R apply(T t)
  35. @Test
  36. public void test2() {
  37. Function<Integer, Employee> func1 = id -> new Employee(id);
  38. Employee employee = func1.apply(1001);
  39. System.out.println(employee);
  40. System.out.println("*******************");
  41. Function<Integer, Employee> func2 = Employee::new;
  42. Employee employee1 = func2.apply(1002);
  43. System.out.println(employee1);
  44. }
  45. //BiFunction中的R apply(T t,U u)
  46. @Test
  47. public void test3() {
  48. BiFunction<Integer, String, Employee> func1 = (id, name) -> new Employee(id, name);
  49. System.out.println(func1.apply(1001, "Tom"));
  50. System.out.println("*******************");
  51. BiFunction<Integer, String, Employee> func2 = Employee::new;
  52. System.out.println(func2.apply(1002, "Tom"));
  53. }
  54. //数组引用
  55. //Function中的R apply(T t)
  56. @Test
  57. public void test4() {
  58. Function<Integer, String[]> func1 = length -> new String[length];
  59. String[] arr1 = func1.apply(5);
  60. System.out.println(Arrays.toString(arr1));
  61. System.out.println("*******************");
  62. Function<Integer, String[]> func2 = String[]::new;
  63. String[] arr2 = func2.apply(10);
  64. System.out.println(Arrays.toString(arr2));
  65. }
  66. }
复制代码

总结

  • 全新的语法带来了很多的便捷,理解起来可能相对麻烦
  • 这里在改变语法为Lambda的时候,可以自己找找可以省去,那一些部分
  • 思考,为什么构造器引用可以根据数量和类型去找到对应的构造器

来源:https://blog.csdn.net/doomwatcher/article/details/121877131
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行