10、函数式接口


主要内容

  • 自定义函数式接口
  • 函数式编程
  • 常用函数式接口

学习目标

  • 能够使用@FunctionalInterface 注解
  • 能够自定义函数式接口
  • 能够理解 Lambda 延迟执行的特点
  • 能够使用 Lambda 作为方法的参数
  • 能够使用 Lambda 作为方法的返回值
  • 能够使用 Supplier 函数式接口
  • 能够使用 Consumer 函数式接口
  • 能够使用 Function 函数式接口
  • 能够使用 Predicate 函数式接口

一、函数式接口

概念
函数式接口在 Java 中是指:有且仅有一个抽象方法(被 abstract 修饰)的接口
函数式接口,即适用于函数式编程场景的接口。而 Java 中的函数式编程体现就是 Lambda,所以函数式接口就是可
以适用于 Lambda 使用的接口。只有确保接口中有且仅有一个抽象方法,Java 中的 Lambda 才能顺利地进行推导。

备注:“语法糖”是指使用更加方便,但是原理不变的代码语法。例如在遍历集合时使用的 for-each 语法,其实 底层的实现原理仍然是迭代器,这便是“语法糖”。从应用层面来讲,Java 中的 Lambda 可以被当做是匿名内部 类的“语法糖”,但是二者在原理上是不同的。

格式
只要确保接口中有且仅有一个抽象方法即可:

修饰符 interface 接口名称 {
    public abstract 返回值类型 方法名称(可选参数信息);
    // 其他非抽象方法内容
}

由于接口当中抽象方法的 public abstract 是可以省略的,所以定义一个函数式接口很简单:

public interface MyFunctionalInterface {
    void myMethod(); 	//接口中的方法都是抽象方法,所以public abstract可以省略
}

**_@_FunctionalInterface **注解(装饰器)
_@_Override 注解的作用类似,Java 8 中专门为函数式接口引入了一个新的注解: _@_FunctionalInterface 。该注
解可用于一个接口的定义上:

@FunctionalInterface
public interface MyFunctionalInterface {
    void myMethod();
}

一旦使用该注解来定义接口,编译器将会强制检查该接口是否确实有且仅有一个抽象方法,否则将会报错。需要
的是,即使不使用该注解,只要满足函数式接口的定义,这仍然是一个函数式接口,使用起来都一样。

自定义函数式接口

对于刚刚定义好的 MyFunctionalInterface 函数式接口,典型使用场景就是作为方法的参数:

//自定义函数式接口(只有一个抽象方法)
@FunctionalInterface
public interface MyFuncInterface {
    void MyMethod();
}
public class Demo01 {
    //使用自定义的函数式接口作为方法参数
    private static void doSomething(MyFuncInterface funcinter){
        funcinter.MyMethod();
    }
    public static void main(String[] args) {
        //调用函数式接口的方法
         doSomething(() ->{
             System.out.println("自定义函数式接口的lambda方法执行了");
         });
    }
}

二、函数式编程

在兼顾面向对象特性的基础上,Java 语言通过 Lambda 表达式与方法引用等,为开发者打开了函数式编程的大门。
下面我们做一个初探。

1.Lambda 的延迟执行

有些场景的代码执行后,结果不一定会被使用但还是编译执行了,从而造成性能浪费。而 Lambda 表达式是延迟执行的,这正好可以 作为解决方案,提升性能。

性能浪费的日志案例

注:日志可以帮助我们快速的定位问题,记录程序运行过程中的情况,以便项目的监控和优化。 一种典型的场景就是对参数进行有条件使用,例如对日志消息进行拼接后,在满足条件的情况下进行打印输出:

private static void log(int level, String msg) {
    if (level == 1) {
        System.out.println(msg);
    }
}
//使用lambda
private static void LambdaLog(int level,BuildMessage builder){
    System.out.println("调用日志方法");
    //执行到这里,判断level == 1,如果不等于lambda中的函数体不执行
    if (level == 1){
        System.out.println(builder.buildMsg());
    }
}
public static void main(String[] args) {
    String msgA = "Hello";
    String msgB = "World";
    String msgC = "Java";
    log(1, msgA + msgB + msgC);		//无论level ==1字符串都进行了拼接,造成性能浪费
    //lambda延迟执行
    LambdaLog(2, () ->{
        System.out.println("lambda方法拼接字符串");
        return msgA + msgB + msgC;
    });
}

这段代码存在问题:无论级别是否满足要求,作为 log 方法的第二个参数,三个字符串一定会首先被拼接并传入方
法内,然后才会进行级别判断。如果级别不符合要求,那么字符串的拼接操作就白做了,存在性能浪费。

备注:SLF4J 是应用非常广泛的日志框架,它在记录日志时为了解决这种性能浪费的问题,并不推荐首先进行 字符串的拼接,而是将字符串的若干部分作为可变参数传入方法中,仅在日志级别满足要求的情况下才会进 行字符串拼接。例如: LOGGER.debug(“变量{}的取值为{}”, “os”, “macOS”) ,其中的大括号 {} 为占位 符。如果满足日志级别要求,则会将“os”和“macOS”两个字符串依次拼接到大括号的位置;否则不会进行字 符串拼接。这也是一种可行解决方案,但 Lambda 可以做到更好。

定义函数式接口:

@FunctionalInterface
public interface BuildMessage {
   String buildMsg();
}

这样一来,只有当级别满足要求的时候,才会进行三个字符串的拼接;否则三个字符串将不会进行拼接。

2.Lambda 作为参数和返回值

如果抛开实现原理不说,Java 中的 Lambda 表达式可以被当作是匿名内部类的替代品。如果方法的参数是一个函数
式接口类型,那么就可以使用 Lambda 表达式进行替代。使用 Lambda 表达式作为方法参数,其实就是使用函数式
接口作为方法参数。
例如 java.lang.Runnable 接口就是一个函数式接口,假设有一个startThread 方法使用该接口作为参数,那么就 可以使用 Lambda 进行传参。这种情况其实和 Thread 类的构造方法参数为 Runnable 没有本质区别。

public class Demo04Runnable {
    private static void startThread(Runnable task) {
        new Thread(task).start();
    }
public static void main(String[] args) {
    startThread(()> System.out.println("线程任务执行!"));
}}

类似地,如果一个方法的返回值类型是一个函数式接口,那么就可以直接返回一个 Lambda 表达式。当需要通过一
个方法来获取一个 java.util.Comparator接口类型的对象作为排序器时,就可以调该方法获取。

public class Demo06Comparator {
    private static Comparator<String> newComparator() {		//返回一个比较器类型
        return (a,b)>b.length() ‐a.length();
    }
    public static void main(String[] args) {
        String[] array = {"abc", "ab", "abcd"};
        System.out.println(Arrays.toString(array));
        Arrays.sort(array, newComparator());
        System.out.println(Arrays.toString(array));
    }
}

其中直接 return 一个 Lambda 表达式即可。

三、常用函数式接口

JDK 提供了大量常用的函数式接口以丰富 Lambda 的典型使用场景,它们主要在 java.util.function 包中被提供。 下面是最简单的几个接口及使用示例。

1.Supplier 接口

java.util.function.Supplier<T> 接口仅包含一个无参的方法:T get() 。用来获取一个泛型参数指定类型的对 象数据。由于这是一个函数式接口,这也就意味着对应的 Lambda 表达式需要“对外提供”一个符合泛型类型的对象数据。

public class Demo01Supplier {
    public static void main(String[] args) {
        String msgA = "hello";
        String msgB = "world";
        System.out.println(getString(()->{
            return msgA+msgB;
        }));
    }
    private static String getString(Supplier<String> func) {
        return func.get();
    }
}

练习:求数组元素最大值
题目
使用 Supplier 接口作为方法参数类型,通过 Lambda 表达式求出 int 数组中的最大值。提示:接口的泛型请使用
java.lang.Integer 类。
解答

public class MaxValueArr {
    public static void main(String[] args) {
        int[] arr = {2,3,5,9,12,65,32};
        int maxNum = getMax(()->{
            int max = arr[0];
            for (int i : arr) {
                if(i>max){
                    max = i;
                }
            }
            return max;
        });
        System.out.println("arr中max="+maxNum);
    }
    private static int getMax(Supplier<Integer> func) {
        return func.get();
    }
}

2.Consumer 接口

java.util.function.Consumer<T> 接口则正好与 Supplier 接口相反,它不是生产一个数据,而是消费一个数据,其数据类型由泛型决定。
抽象方法:accept
Consumer 接口中包含抽象方法 void accept(T t) ,意为消费一个指定泛型的数据。基本使用如:

//jdk8用法
Consumer<String> consumer = new Consumer<>() {
    @Override
    public void accept(String s) {
        System.out.println("s="+s);
    }
};
//lambda写法
Consumer<String> consumer = s -> System.out.println("s="+s);
consumer.accept("hello world");
//andThen链式调用
Consumer<String> consumer1 = s -> {
    s+=" xiong";
    System.out.println("s="+s);
};
Consumer<String> consumer2 = s -> {
    s+=" world";        //接收的s还是accept传入的参数
    System.out.println("s="+s);
};
consumer1.andThen(consumer2).accept("Justin");

当然还可以将 lambda 方法写到 Consumer 中,像调用普通函数一样

public static void main(String[] args) {
        consumerStr();
        testAndThen();
}
private static void consumerStr() {
    Consumer<Integer> function = x->{
        System.out.println("x*x="+x*x);
    };
    function.accept(2);
}
/**
* 定义3个Consumer并按顺序进行调用andThen方法,其中consumer2抛出NullPointerException。
*/
public static void testAndThen(){
    Consumer<Integer> consumer1 = x -> System.out.println("first x : " + x);
    Consumer<Integer> consumer2 = x -> {
        System.out.println("second x : " + x);
        throw new NullPointerException("throw exception test");     //抛出异常
    };
    Consumer<Integer> consumer3 = x -> System.out.println("third x : " + x);
	//consumer2执行完抛出异常,consumer3未执行
    consumer1.andThen(consumer2).andThen(consumer3).accept(1);
}

练习:打印集合列表的每一项 item 信息
定义一个 Employee 类

arr.forEach(Consumer<? super T> action) 传入 Consumer

private static final List<Employee> employees = Arrays.asList(new Employee(1,"zhangsan"),
       					new Employee(2,"lisi"),new Employee(3,"wagnwu"));
public static void main(String[] args) {
    Consumer<Employee> consumer = employee -> System.out.println(employee);
    employees.forEach(consumer);
}
//打印
//Employee{id=1, name='zhangsan'}
//Employee{id=2, name='lisi'}
//Employee{id=3, name='wagnwu'}

练习:格式化打印信息
题目
下面的字符串数组当中存有多条信息,请按照格式“ 姓名:XX。性别:XX。 ”的格式将信息打印出来。要求将打印姓 名的动作作为第一个 Consumer 接口的 Lambda 实例,将打印性别的动作作为第二个 Consumer 接口的 Lambda 实 例,将两个 Consumer 接口按照顺序“拼接”到一起。

public class FormatInfo {
    public static void main(String[] args) {
        String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男" };
        printInfo(array,
                s -> System.out.println("姓名:"+s.split(",")[0]),
                s -> System.out.println("性别:"+s.split(",")[1]));
    }
    private static void printInfo(String[] array,Consumer<String> con1,Consumer<String> con2) {
        for (String s : array) {
            con1.andThen(con2).accept(s);
        }
    }
}

打印:

姓名:迪丽热巴
性别:女
姓名:古力娜扎
性别:女
姓名:马尔扎哈
性别:男

3.Predicate 接口

有时候我们需要对某种类型的数据进行判断,从而得到一个 boolean 值结果。这时可以使用
java.util.function.Predicate<T> 接口。
抽象方法:test
Predicate 接口中包含一个抽象方法:boolean test(T t)。用于条件判断的场景:

public class Demo01Predicate {
    public static void main(String[] args) {
        String str = "hello world";
        strIsLong(str,s -> {
            return s.length()>20;
        });
    }
    private static void strIsLong(String str,Predicate<String> pre){
        boolean isLong = pre.test(str);		//pre.test(str)  结果就是lambda返回值
        System.out.println(str+"字符串长吗? "+isLong);
    }
}

条件判断的标准是传入的 Lambda 表达式逻辑,只要字符串长度大于 20 则认为很长。
默认方法:and
既然是条件判断,就会存在与、或、非三种常见的逻辑关系。其中将两个 Predicate 条件使用“与”逻辑连接起来实
现“并且”的效果时,可以使用 default 方法 and 。其 JDK 源码为

default Predicate<T> and(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t)> test(t) && other.test(t);
}

如果要判断一个字符串既要包含大写“H”,又要包含大写“W”,那么:

public static void main(String[] args) {
    PredicateAnd("HelloWorld",
                    s -> s.contains("H"),
                    s -> s.contains("W"));
}
private static void PredicateAnd(String str,Predicate<String> one,Predicate<String> two){
    boolean isValid = one.and(two).test(str);
    System.out.println("字符串符合要求吗? "+isValid);
}

默认方法:or
与 and 的“与”类似,默认方法 or 实现逻辑关系中的“”。JDK 源码为:

default Predicate<T> or(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t)> test(t) || other.test(t);
}

如果希望实现逻辑“字符串包含大写 H 或者包含大写 W”,那么代码只需要将“and”修改为“or”名称即可,其他都不
变:

public static void main(String[] args) {
    PredicateOr("HelloWorld",
                    s -> s.contains("H"),
                    s -> s.contains("W"));
}
private static void PredicateOr(String str,Predicate<String> one,Predicate<String> two){
    boolean isValid = one.or(two).test(str);
    System.out.println("字符串符合要求吗? "+isValid);
}

默认方法:negate
“与”、“或”已经了解了,剩下的“非”(取反)也会简单。默认方法 negate 的 JDK 源代码为:

default Predicate<T> negate() {
    return (t)> !test(t);
}

从实现中很容易看出,它是执行了 test 方法之后,对结果 boolean 值进行“!”取反而已。一定要在 test 方法调用之前
调用 negate 方法,正如 and 和 or 方法一样:

public static void main(String[] args) {
    //非,判断一个字符串包含大写“H”的情况取反
    PredicateNegate("HelloWorld",
                    s -> s.contains("H"));
}
private static void PredicateNegate(String str,Predicate<String> one){
    boolean isValid = one.negate().test(str);
    System.out.println("negate字符串符合要求吗? "+isValid);
}

练习:集合信息筛选
题目
数组当中有多条“姓名+性别”的信息如下,请通过 Predicate 接口的拼装将符合要求的字符串筛选到集合
ArrayList 中,需要同时满足两个条件:

  1. 必须为女生;

  2. 姓名为 4 个字。

public class Test01Predicate {
    public static void main(String[] args) {
        String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男", "赵丽颖,女" };
        List<String> lis  = filterArray(array,
                s -> s.split(",")[0].length() == 4,
                s -> s.split(",")[1].equals("女"));
        System.out.println(lis);
    }
    //必须为女生 并且 姓名为4个字。
    private static List<String> filterArray(String[] arr, Predicate<String> one,Predicate<String> two) {
        List<String> li = new ArrayList<>();
        for (String item : arr) {
            System.out.println("------->"+item);
            if(one.and(two).test(item)){
                System.out.println("==========="+item);
                li.add(""+item);
            }
        }
        return li;
    }
}

4.Function 接口

java.util.function.Function<T,R> 接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件, 后者称为后置条件。
抽象方法:apply
Function 接口中最主要的抽象方法为: R apply(T t) ,根据类型 T 的参数获取类型 R 的结果。
使用的场景例如:将 String 类型转换为 Integer 类型。

private static void method(Function<String,Integer> function) {
    int num = function.apply("10");
    System.out.println(num + 20);
}
public static void main(String[] args) {
    method(s ->Integer.parseInt(s));
}

当然,最好是通过方法引用的写法。
默认方法:andThen
Function 接口中有一个默认的 andThen 方法,用来进行组合操作。
该方法同样用于“先做什么,再做什么”的场景,和 Consumer 中的 andThen 差不多:

public static void main(String[] args) {
    //andThen链式
    functionAndThen(str ->Integer.parseInt(str)+10,
                    i -> i *= 2);
}
private static void functionAndThen(Function<String ,Integer> one,
                                    Function<Integer ,Integer> two) {
    int num = one.andThen(two).apply("10");   //10+10 = 20,20*2=40
    System.out.println(num+20);     //40+20=60
}

第一个操作是将字符串解析成为 int 数字并加上 10,第二个操作是将第一个操作处理得到的结果乘以 2。两个操作通过 andThen 按照前后顺序组合到了一 起。

请注意,Function 的前置条件泛型和后置条件泛型可以相同。
Function<String ,Integer> one 处理之前是 String ,处理之后是 Integer
Function<Integer,Integer> one 处理之前是 Integer ,处理之后还是 Integer

练习:自定义函数模型拼接
题目
请使用 Function 进行函数模型的拼接,按照顺序需要执行的多个函数操作为:
String str = “赵丽颖,20”;

  1. 将字符串截取数字年龄部分,得到字符串;

  2. 将上一步的字符串转换成为 int 类型的数字;

  3. 将上一步的 int 数字累加 100,得到结果 int 数字。

解答

综合练习
如果是一个数组怎么办呢?
String[] array = { "迪丽热巴,女,23", "古力娜扎,女,16", "马尔扎哈,男,32", "赵丽颖,女,20" };
要求:

  • 名字必须是 4 个字,且必须是女的
  • 年龄+100
public class Test02 {
    public static void main(String[] args) {
        String[] array = { "迪丽热巴,女,23", "古力娜扎,女,16", "马尔扎哈,男,32", "赵丽颖,女,20" };
        List<String> actorList = getActorList(array,
                s -> "女".equals(s.split(",")[1]),
                s -> s.split(",")[0].length() == 4,
                s -> {
                    int age = Integer.parseInt(s.split(",")[2]);
                    String[] strList = s.split(",");
                    strList[2] = String.valueOf(age+100);
                    String item = "";
                    for (String s1 : strList) {
                        item=item+s1+",";
                    }
                    return item.substring(0,item.length()-1);
                }
        );
        System.out.println(actorList);
    }
    private static List<String> getActorList(String[] array, Predicate<String> pred1, Predicate<String> pred2,
                                          Function<String,String> func) {
        ArrayList<String> strings = new ArrayList<>();
        for (String item : array) {
            if(pred1.and(pred2).test(item)){
                String s =  func.apply(item);
                strings.add(s);
            }
        }
        return strings;
    }
}

打印结果:

[迪丽热巴,女,123, 古力娜扎,女,116]


文章作者: CoderXiong
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 CoderXiong !
  目录