函数式接口、方法引用

主要内容

  • 函数式接口
  • 方法引用

教学目标

  • 能够使用@FunctionalInterface注解
  • 能够自定义无参无返回函数式接口
  • 能够自定义有参有返回函数式接口
  • 能够理解Lambda延迟执行的特点
  • 能够使用Lambda作为方法的参数
  • 能够使用Lambda作为方法的返回值
  • 能够使用输出语句的方法引用
  • 能够通过4种方式使用方法引用
  • 能够使用类和数组的构造器引用
  • 能够使用Supplier函数式接口
  • 能够使用Consumer函数式接口

第一章 函数式接口

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-G0bIKkdN-1582364164814)(assets/1550397000139.png)]

1.1 概念

函数式接口在Java中是指:有且仅有一个抽象方法的接口。

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

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

1.2 格式

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

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

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

public interface MyFunctionalInterface {
    void myMethod();
}

1.3 @FunctionalInterface注解

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d0U4VxJo-1582364164816)(assets/1550397095072.png)]

与@Override 注解的作用类似,Java 8中专门为函数式接口引入了一个新的注解: @FunctionalInterface 。该注解可用于一个接口的定义上:

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

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

1.4 练习:自定义函数式接口(无参无返回)

题目
请定义一个函数式接口Eatable ,内含抽象eat 方法,没有参数或返回值。使用该接口作为方法的参数,并进而通过Lambda来使用它。

解答

函数式接口的定义:

@FunctionalInterface
public interface Eatable {
    void eat();
}

应用场景代码:

public class DemoLambdaEatable {
    private static void keepAlive(Eatable human) {
        human.eat();
    }
    public static void main(String[] args) {
        keepAlive(()> System.out.println("吃饭饭!"));
    }
}

1.5 练习:自定义函数式接口(有参有返回)

题目

请定义一个函数式接口Sumable ,内含抽象sum 方法,可以将两个int数字相加返回int结果。使用该接口作为方法的参数,并进而通过Lambda来使用它。

解答

函数式接口的定义:

@FunctionalInterface
public interface Sumable {
    int sum(int a, int b);
}

应用场景代码:

public class DemoLambdaSumable {
    private static void showSum(int x, int y, Sumable sumCalculator) {
        System.out.println(sumCalculator.sum(x, y));
    }
    public static void main(String[] args) {
        showSum(10, 20, (m, n)> m + n);
    }
}

第二章 函数式编程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DdlCaoEj-1582364164817)(assets/1550397919201.png)]

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

2.1 Lambda的延迟执行

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yluex8H9-1582364164818)(assets/1550401129763.png)]

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

性能浪费的日志案例

一种典型的场景就是对参数进行有条件使用,例如对日志消息进行拼接后,在满足条件的情况下进行打印输出:

public class Demo01Logger {
    private static void log(int level, String msg) {
        if (level == 1) {
            System.out.println(msg);
        }
    }
    public static void main(String[] args) {
        String msgA = "Hello";
        String msgB = "World";
        String msgC = "Java";
        log(1, msgA + msgB + msgC);
    }
}

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

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

体验Lambda的更优写法

使用Lambda必然需要一个函数式接口:

@FunctionalInterface
public interface MessageBuilder {
    String buildMessage();
}

然后对log 方法进行改造:

public class Demo02LoggerLambda {
    private static void log(int level, MessageBuilder builder) {
        if (level == 1) {
            System.out.println(builder.buildMessage());
        }
    }
    public static void main(String[] args) {
        String msgA = "Hello";
        String msgB = "World";
        String msgC = "Java";
        log(1, ()> msgA + msgB + msgC );
    }
}

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

证明Lambda的延迟
下面的代码可以通过结果进行验证:

public class Demo03LoggerDelay {
    private static void log(int level, MessageBuilder builder) {
        if (level == 1) {
            System.out.println(builder.buildMessage());
        }
    }
    public static void main(String[] args) {
        String msgA = "Hello";
        String msgB = "World";
        String msgC = "Java";
        log(2, ()> {
            System.out.println("Lambda执行!");
            return msgA + msgB + msgC;
        });
    }
}

从结果中可以看出,在不符合级别要求的情况下,Lambda将不会执行。从而达到节省性能的效果。

扩展:实际上使用内部类也可以达到同样的效果,只是将代码操作延迟到了另外一个对象当中通过调用方法
来完成。而是否调用其所在方法是在条件判断之后才执行的。

2.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 接口类型的对象作为排序器时:

import java.util.Arrays;
import 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表达式即可。

第三章 方法引用

3.1 方法引用概述

3.1.1 什么是方法引用

通过类名或对象名引用已经存在的方法来简化lambda表达式。

3.1.2 方法引用的格式

  • 类名::方法名
  • 对象名::方法名

3.1.3 方法引用的原理

  • 创建了函数式接口的匿名内部类对象
  • 重写了函数式接口的抽象方法并在重写的方法中调用被引用的方法。

3.1.4 方法引用的四种类型

  • 静态方法引用:通过类名引用
  • 对象方法引用:通过对象名引用
  • 特定类型的实例方法引用
  • 构造方法的引用

3.1.5 方法引用的好处

  • 简化了lambda表达式
  • 重复利用已经存在的方法

3.2 方法引用的四种类型

3.2.1 静态方法引用

  • 语法格式:ClassName::staticMethodName

注意事项

  • 被引用的方法和函数式接口中的抽象方法必须有相同的参数列表。
  • 如果函数式接口中的抽象方法有返回值,则被引用的方法必须也有相同的返回值。
  • 如果函数式接口中的抽象方法没有返回值,则被引用的方法可以有返回值,也可以没有返回值。

示例代码

  • 函数式接口
@FunctionalInterface
public interface ArrayHelper {
    // 获得数组最大值
    int getMax(int[] arr);
}
  • 数组工具类
public class ArrayUtil {
    /**
    * 求数组的最大值
    */
    public static int max(int[] arr){
        int max = arr[0];
        for (int index = 1; index < arr.length; index ++) {
            if (arr[index] > max){
                max = arr[index];
            }
        }
        return max;
    }
}
  • 测试类
/*
* 方法引用之静态方法引用:通过类名引用 格式是 ==> 类名::方法名
*/
public class MethodRefDemo01 {
    public static void main(String[] args){
        // 定义整型数组
        int[] arr = {1,2,3,4,5,6,7,8};
        // 使用匿名内部类创建ArrayHelper实现类对象
        ArrayHelper helper = new ArrayHelper() {
            @Override
            public int getMax(int[] arr) {
                int max = arr[0];
                for (int index = 1; index < arr.length; index ++) {
                    if (arr[index] > max){
                        max = arr[index];
                    }
                }
                return max;
            }
        };
        // 获得数组最大值
        int maxValue = helper.getMax(arr);
        System.out.println(maxValue);
        
        // 使用lambda表达式创建ArrayHelper实现类对象
        ArrayHelper helper01 = arr1 ‐> {
            int max = arr[0];
            for (int index = 1; index < arr.length; index ++) {
                if (arr[index] > max){
                    max = arr[index];
                }
            }
            return max;
        };
        // 获得数组最大值
        int maxValue01 = helper01.getMax(arr);
        System.out.println(maxValue01);
        
        // 使用方法引用创建ArrayHelper实现类对象
        ArrayHelper helper02 = ArrayUtil::max;
        // 获得数组最大值
        int maxValue02 = helper02.getMax(arr);
        System.out.println(maxValue02);
    }
}

3.2.2 对象方法引用

语法格式:instance::methodName

和静态方法的语法类似,只不过这里使用对象引用而不是类名。

注意事项

  • 被引用的方法和函数式接口中的抽象方法必须有相同的参数列表。
  • 如果函数式接口中的抽象方法有返回值,则被引用的方法必须也有相同的返回值。
  • 如果函数式接口中的抽象方法没有返回值,则被引用的方法可以有返回值,也可以没有返回值。

示例代码1

函数式接口

public interface NumHepler {
    // 返回a到b之间的随机数
    int nextIntFormAToB(int a,int b);
}

自定义随机数类

public class MyRandom {
    /**
    * 随机产生一个A到B之间的随机数 比如a = 100,b == 200 返回一个100到200之间的随机数
    */
    public int nextAToB(int a,int b){
        Random r = new Random();
        return r.nextInt(b ‐ a + 1) + a;
    }
}

测试类

/*
*方法引用之对象方法引用:通过对象名引用 格式 ==> 对象名::方法名
*/
public class MethodRefDemo02{
    public static void main(String[] args){
        // 使用匿名内部创建NumHepler接口实现类对象
        NumHepler nh01 = new NumHepler(){
            @Override
            public int nextIntFormAToB(int a, int b) {
                Random r = new Random();
                return r.nextInt(b ‐ a + 1) + a;
            }
        };
        // 随机生成一个100到200之间的整数
        System.out.println(nh01.nextIntFormAToB(100,200));
        // 使用lambda表达式创建NumHepler接口实现类对象
        NumHepler nh02 = (a, b)> {
            Random r = new Random();
            return r.nextInt(b ‐ a + 1) + a;
        };
        // 随机生成一个200到500之间的整数
        System.out.println(nh02.nextIntFormAToB(200,500));
        // 创建MyRandom类对象
        MyRandom r = new MyRandom();
        // 使用方法引用创建NumHepler接口实现类对象
        NumHepler nh03 = r::nextAToB;
        // 随机生成一个500到1000之间的整数
        System.out.println(nh03.nextIntFormAToB(500,1000));
    }
}

示例代码2

public class MethodRfDemo02 {
    public static void main(String[] args){
        // 创建集合对象
        List<Person> persons = new ArrayList<>();
        persons.add(new Person("李四",24));
        persons.add(new Person("张三",23));
        persons.add(new Person("老王",25));
        // 遍历集合并输出元素
        // persons.forEach( p ‐> System.out.println(p));
        // 引用的方法是打印流对象的println方法。
        persons.forEach(System.out::println);
    }
}

3.2.3 构造方法引用

语法格式:Class::new

构造函数本质上是静态方法,只是方法名字比较特殊,使用的是new 关键字。

注意事项

  • 函数式接口中的抽象方法返回值是引用数据类型
  • 类中必须存在一个参数列表与函数式接口的参数列表相同的构造方法

示例代码

函数式接口

@FunctionalInterface
public interface CarFactory {
    Car makeCar(String brand);
}

定义一个汽车类:Car

public class Car {
    // 品牌
    private String brand;
    public Car(String brand) {
        this.brand = brand;
    }
    public Car() {
    }
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    @Override
    public String toString() {
        return "Car{" +
            "brand='" + brand + '\'' +
            '}';
    }
}

测试类

/*
* 方法引用之构造方法引用:通过类名引用 格式==> 类名::new
*/
public class MethodRefDemo03{
    public static void methodRf03(){
        // 使用匿名内部类创建CarFactory接口实现类对象
        CarFactory cf01 = new CarFactory() {
            @Override
            public Car makeCar(String brand) {
                return new Car(brand);
            }
        };
        // 生成一部宝马车
        Car bmw = cf01.makeCar("宝马");
        System.out.println(bmw);
        // 使用lambda表达式创建CarFactory接口实现类对象
        CarFactory cf02 = brand ‐> new Car(brand);
        // 生产一部奥迪车
        Car audi = cf02.makeCar("奥迪");
        System.out.println(audi);
        // 使用方法引用创建CarFactory接口实现类对象
        CarFactory cf03 = Car::new;
        // 生产一部国产哈佛车
        Car hf = cf03.makeCar("哈佛H6");
        System.out.println(hf);
    }
}

3.2.4 数组构造方法引用

数组也是Object 的子类对象,所以同样具有构造方法,只是语法稍有不同。如果对应到Lambda的使用场景中
时,需要一个函数式接口:

@FunctionalInterface
public interface ArrayBuilder {
    int[] buildArray(int length);
}

在应用该接口的时候,可以通过Lambda表达式:

public class Demo11ArrayInitRef {
    private static int[] initArray(int length, ArrayBuilder builder) {
        return builder.buildArray(length);
    }
    public static void main(String[] args) {
        int[] array = initArray(10, length ‐> new int[length]);
    }
}

但是更好的写法是使用数组的构造方法引用:

public class Demo12ArrayInitRef {
    private static int[] initArray(int length, ArrayBuilder builder) {
        return builder.buildArray(length);
    }
    public static void main(String[] args) {
        int[] array = initArray(10, int[]::new);
    }
}

在这个例子中,下面两种写法是等效的:

  • Lambda表达式: length -> new int[length]
  • 方法引用: int[]::new

3.2.5 特定类型的实例方法引用(了解)

语法格式:类名::实例方法名

注意事项

  • 被引用的方法参数列表要比函数式接口中的抽象方法的参数列表少一个参数。
  • 被引用的方法是由lambda表达式中的第一个参数调用,其余参数作为被引用方法的参数传递。

示例代码

/**
* 特定类型的实例方法引用
*/
public class MethodRfDemo04 {
    public static void main(String[] args){
        String[] stringsArray = {"Barbara", "James", "Mary",
                                 "John", "Patricia", "james", "Michael", "Linda"};
        // 使用lambda表达式
        // Arrays.sort(stringsArray,(s1,s2)‐> s1.compareToIgnoreCase(s2));
        // 特定类型的实例方法引用
        // 引用的是String类型的实例方法
        Arrays.sort(stringsArray, String::compareToIgnoreCase);
        System.out.println(Arrays.toString(stringsArray));
    }
}

这里非常奇怪,sort方法接收的lambda表达式不应该是两个参数么,为什么这个实例方法只有一个参数也满足了lambda表达式的定义(想想这个方法是谁来调用的)。这就是 类名::实例方法名 这种方法引用的特殊之处:当使用 类名::实例方法名 方法引用时,一定是lambda表达式所接收的第一个参数来调用实例方法,如果lambda表达式接收多个参数,其余的参数作为被引用方法的参数传递进去。

结合本例来看,最初的lambda表达式是这样的

Arrays.sort(stringsArray,(s1,s2)> s1.compareToIgnoreCase(s2));

那使用 类名::实例方法名 方法引用时,一定是s1来调用了compareToIgnoreCase实例方法,并将s2作为参数传递进来进行比较。这就符合了compareToIgnoreCase的方法定义。

3.3 方法引用练习

练习01:对象方法引用

题目
假设有一个助理类Assistant ,其中含有成员方法dealFile 如下:

public class Assistant {
    public void dealFile(String file) {
        System.out.println("帮忙处理文件:" + file);
    }
}

请自定义一个函数式接口WorkHelper ,其中的抽象方法help 的预期行为与dealFile 方法一致,并定义一个方法使用该函数式接口作为参数。通过方法引用的形式,将助理对象中的help 方法作为Lambda的实现。

解答
函数式接口可以定义为:

@FunctionalInterface
public interface WorkHelper {
    void help(String file);
}

通过对象名引用成员方法的使用场景代码为:

public class DemoAssistant {
    private static void work(WorkHelper helper) {
        helper.help("机密文件");
    }
    public static void main(String[] args) {
        Assistant assistant = new Assistant();
        work(assistant::dealFile);
    }
}

练习02:静态方法引用
题目
假设有一个StringUtils 字符串工具类,其中含有静态方法isBlank 如下:

public final class StringUtils {
    public static boolean isBlank(String str) {
        return str == null || "".equals(str.trim());
    }
}

请自定义一个函数式接口StringChecker ,其中的抽象方法checkBlank 的预期行为与isBlank 一致,并定义一个方法使用该函数式接口作为参数。通过方法引用的形式,将StringUtils 工具类中的isBlank 方法作为Lambda的
实现。

解答

函数式接口的定义可以为:

@FunctionalInterface
public interface StringChecker {
    boolean checkString(String str);
}

应用场景代码为:

public class DemoStringChecker {
    private static void methodCheck(StringChecker checker) {
        System.out.println(checker.checkString(" "));
    }
    public static void main(String[] args) {
        methodCheck(StringUtils::isBlank);
    }
}

3.4 通过this引用成员方法

this代表当前对象,如果需要引用的方法就是当前类中的成员方法,那么可以使用“this::成员方法”的格式来使用方法引用。首先是简单的函数式接口:

@FunctionalInterface
public interface Richable {
    void buy();
}

下面是一个丈夫Husband 类:

public class Husband {
    private void marry(Richable lambda) {
        lambda.buy();
    }
    public void beHappy() {
        marry(()> System.out.println("买套房子"));
    }
}

开心方法beHappy 调用了结婚方法marry ,后者的参数为函数式接口Richable ,所以需要一个Lambda表达式。但是如果这个Lambda表达式的内容已经在本类当中存在了,则可以对Husband 丈夫类进行修改:

public class Husband {
    private void buyHouse() {
        System.out.println("买套房子");
    }
    private void marry(Richable lambda) {
        lambda.buy();
    }
    public void beHappy() {
        marry(()> this.buyHouse());
    }
}

如果希望取消掉Lambda表达式,用方法引用进行替换,则更好的写法为:

public class Husband {
    private void buyHouse() {
        System.out.println("买套房子");
    }
    private void marry(Richable lambda) {
        lambda.buy();
    }
    public void beHappy() {
        marry(this::buyHouse);
    }
}

在这个例子中,下面两种写法是等效的:

  • Lambda表达式: () -> this.buyHouse()
  • 方法引用: this::buyHouse

3.5 通过super引用成员方法

如果存在继承关系,当Lambda中需要出现super调用时,也可以使用方法引用进行替代。

首先是函数式接口

@FunctionalInterface
public interface Greetable {
    void greet();
}

然后是父类Human 的内容:

public class Human {
    public void sayHello() {
        System.out.println("Hello!");
    }
}

最后是子类Man 的内容,其中使用了Lambda的写法:

public class Man extends Human {
    @Override
    public void sayHello() {
        method(()> super.sayHello());
    }
    private void method(Greetable lambda) {
        lambda.greet();
        System.out.println("I'm a man!");
    }
}

但是如果使用方法引用来调用父类中的sayHello 方法会更好,例如另一个子类Woman :

public class Woman extends Human {
    @Override
    public void sayHello() {
        method(super::sayHello);
    }
    private void method(Greetable lambda) {
        lambda.greet();
        System.out.println("I'm a woman!");
    }
}

在这个例子中,下面两种写法是等效的:

  • Lambda表达式: () -> super.sayHello()
  • 方法引用: super::sayHello

第四章 常用函数式接口

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KHHs5Uq8-1582364164820)(assets/1550403643218.png)]

JDK提供了大量常用的函数式接口以丰富Lambda的典型使用场景,它们主要在java.util.function 包中被提供。前文的MySupplier 接口就是在模拟一个函数式接口:java.util.function.Supplier<T>。其实还有很多,下面是最简单的几个接口及使用示例。

4.1 Supplier接口

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

import java.util.function.Supplier;
public class Demo08Supplier {
    private static String getString(Supplier<String> function) {
        return function.get();
    }
    public static void main(String[] args) {
        String msgA = "Hello";
        String msgB = "World";
        System.out.println(getString(()> msgA + msgB));
    }
}

备注:其实这个接口在前面的练习中已经模拟过了。

4.2 练习:求数组元素最大值

题目

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

解答

import java.util.function.Supplier;
public class DemoIntArray {
    public static void main(String[] args) {
        int[] array = { 10, 20, 100, 30, 40, 50 };
        printMax(()> {
            int max = array[0];
            for (int i = 1; i < array.length; i++) {
                if (array[i] > max) {
                    max = array[i];
                }
            }
            return max;
        });
    }
    private static void printMax(Supplier<Integer> supplier) {
        int max = supplier.get();
        System.out.println(max);
    }
}

4.3 Consumer接口

java.util.function.Consumer<T>接口则正好相反,它不是生产一个数据,而是消费一个数据,其数据类型由泛型参数决定。

抽象方法:accept

Consumer 接口中包含抽象方法void accept(T t),意为消费一个指定泛型的数据。基本使用如:
当然,更好的写法是使用方法引用。

import java.util.function.Consumer;
public class Demo09Consumer {
    private static void consumeString(Consumer<String> function) {
        function.accept("Hello");
    }
    public static void main(String[] args) {
        consumeString(s ‐> System.out.println(s));
        consumeString(System.out::println);
    }
}

默认方法:andThen

如果一个方法的参数和返回值全都是Consumer 类型,那么就可以实现效果:**消费一个数据的时候,首先做一个操作,然后再做一个操作,实现组合。**而这个方法就是Consumer 接口中的default方法andThen 。

下面是JDK的源代码:

default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t)> { accept(t); after.accept(t); };
}

备注: java.util.Objects 的requireNonNull 静态方法将会在参数为null时主动抛出NullPointerException 异常。这省去了重复编写if语句和抛出空指针异常的麻烦。

要想实现组合,需要两个或多个Lambda表达式即可,而andThen 的语义正是“一步接一步”操作。例如两个步骤组合的情况:

import java.util.function.Consumer;
public class Demo10ConsumerAndThen {
    private static void consumeString(Consumer<String> one, Consumer<String> two) {
        one.andThen(two).accept("Hello");
    }
    public static void main(String[] args) {
        consumeString(
            s ‐> System.out.println(s.toUpperCase()),
            s ‐> System.out.println(s.toLowerCase()));
    }
}

运行结果将会首先打印完全大写的HELLO,然后打印完全小写的hello。当然,通过链式写法可以实现更多步骤的组合。

4.4 练习:格式化打印信息

题目

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

public static void main(String[] args) {
    String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男" };
}

解答

import java.util.function.Consumer;
public class DemoConsumer {
    public static void main(String[] args) {
        String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男" };
        printInfo(s ‐> System.out.print("姓名:" + s.split(",")[0]),
                  s ‐> System.out.println("。性别:" + s.split(",")[1] + "。"),
                  array);
    }
    private static void printInfo(Consumer<String> one, Consumer<String> two, String[] array) {
        for (String info : array) {
            one.andThen(two).accept(info); // 姓名:迪丽热巴。性别:女。
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值