Java8新特性:函数式接口,方法与构造器引用

x33g5p2x  于2021-12-11 转载在 Java  
字(8.9k)|赞(0)|评价(0)|浏览(411)

前言

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()
Function<T,R>TR对类型为T的对象应用操作,并返回结果,结果是R类型的对象,包含方法 R apply(T t)
PredicateTboolean确定类型为T的对象是否满足某个约束,并返回boolean值,包含方法 boolean test(T t)

理论+实践

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

方法引用与构造器引用

  • 当前要传递给 Lambda体的操作,已经有了实现的方法了,可以使用方法引用

  • 方法引用可以看做是Lambda表达式的深层次表达,换句话说,方法引用就是Lambda表达式,只不过和之前我们自己编写不同,这里通过方法的名字来指向一个方法,可以认为是Lambda表达式的一种语法糖

  • 要求:实现接口的抽象方法的参数列表和返回值类型。必须与方法引用的方法的参数列表和返回值保持一致

  • 格式:使用操作符“::”将类或者对象与方法名字分开来

  • 如下是三种主要的使用情况

  • 对象::实例方法名

  • 类::静态方法名

  • 类::实例方法名

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

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

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

EmployeeData

  1. package Lambda.MethodReferences;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /** * * @author : <h2>冷环渊</h2> * @date : 2021/12/11 * @context:<h4>提供用于测试的数据</h4> */
  5. public class EmployeeData {
  6. public static List<Employee> getEmployees() {
  7. List<Employee> list = new ArrayList<>();
  8. list.add(new Employee(1001, "马化腾", 34, 6000.38));
  9. list.add(new Employee(1002, "马云", 12, 9876.12));
  10. list.add(new Employee(1003, "刘强东", 33, 3000.82));
  11. list.add(new Employee(1004, "雷军", 26, 7657.37));
  12. list.add(new Employee(1005, "李彦宏", 65, 5555.32));
  13. list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
  14. list.add(new Employee(1007, "任正非", 26, 4333.32));
  15. list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
  16. return list;
  17. }
  18. }
  1. /** * @author : <h2>冷环渊</h2> * @date : 2021/12/11 * @context:<h4> * 方法引用的使用 * * 1.使用情境:当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用! * 2.方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以 * 方法引用,也是函数式接口的实例。 * 3. 使用格式: 类(或对象) :: 方法名 * 4. 具体分为如下的三种情况: * 情况1 对象 :: 非静态方法 * 情况2 类 :: 静态方法 * 情况3 类 :: 非静态方法 * 5. 方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的 * 形参列表和返回值类型相同!(针对于情况1和情况2) * * </h4> * */
  2. public class MethodRefTest {
  3. // 情况一:对象 :: 实例方法
  4. //Consumer中的void accept(T t)
  5. //PrintStream中的void println(T t)
  6. @Test
  7. public void test1() {
  8. Consumer<String> con1 = str -> System.out.println(str);
  9. con1.accept("北京");
  10. System.out.println("*******************");
  11. PrintStream ps = System.out;
  12. Consumer<String> con2 = ps::println;
  13. con2.accept("beijing");
  14. }
  15. //Supplier中的T get()
  16. //Employee中的String getName()
  17. @Test
  18. public void test2() {
  19. Employee emp = new Employee(1001, "Tom", 23, 5600);
  20. Supplier<String> sup1 = () -> emp.getName();
  21. System.out.println(sup1.get());
  22. System.out.println("*******************");
  23. Supplier<String> sup2 = emp::getName;
  24. System.out.println(sup2.get());
  25. }
  26. // 情况二:类 :: 静态方法
  27. //Comparator中的int compare(T t1,T t2)
  28. //Integer中的int compare(T t1,T t2)
  29. @Test
  30. public void test3() {
  31. Comparator<Integer> com1 = (t1, t2) -> Integer.compare(t1, t2);
  32. System.out.println(com1.compare(12, 21));
  33. System.out.println("*******************");
  34. Comparator<Integer> com2 = Integer::compare;
  35. System.out.println(com2.compare(12, 3));
  36. }
  37. //Function中的R apply(T t)
  38. //Math中的Long round(Double d)
  39. @Test
  40. public void test4() {
  41. Function<Double, Long> func = new Function<Double, Long>() {
  42. @Override
  43. public Long apply(Double d) {
  44. return Math.round(d);
  45. }
  46. };
  47. System.out.println("*******************");
  48. Function<Double, Long> func1 = d -> Math.round(d);
  49. System.out.println(func1.apply(12.3));
  50. System.out.println("*******************");
  51. Function<Double, Long> func2 = Math::round;
  52. System.out.println(func2.apply(12.6));
  53. }
  54. // 情况三:类 :: 实例方法 (有难度)
  55. // Comparator中的int comapre(T t1,T t2)
  56. // String中的int t1.compareTo(t2)
  57. @Test
  58. public void test5() {
  59. Comparator<String> com1 = (s1, s2) -> s1.compareTo(s2);
  60. System.out.println(com1.compare("abc", "abd"));
  61. System.out.println("*******************");
  62. Comparator<String> com2 = String::compareTo;
  63. System.out.println(com2.compare("abd", "abm"));
  64. }
  65. //BiPredicate中的boolean test(T t1, T t2);
  66. //String中的boolean t1.equals(t2)
  67. @Test
  68. public void test6() {
  69. BiPredicate<String, String> pre1 = (s1, s2) -> s1.equals(s2);
  70. System.out.println(pre1.test("abc", "abc"));
  71. System.out.println("*******************");
  72. BiPredicate<String, String> pre2 = String::equals;
  73. System.out.println(pre2.test("abc", "abd"));
  74. }
  75. // Function中的R apply(T t)
  76. // Employee中的String getName();
  77. @Test
  78. public void test7() {
  79. Employee employee = new Employee(1001, "Jerry", 23, 6000);
  80. Function<Employee, String> func1 = e -> e.getName();
  81. System.out.println(func1.apply(employee));
  82. System.out.println("*******************");
  83. Function<Employee, String> func2 = Employee::getName;
  84. System.out.println(func2.apply(employee));
  85. }
  86. }

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

一、构造器引用

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

二、数组引用

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

总结

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

相关文章

最新文章

更多