BiConsumer 接口提供了两个重要的方法:andThen() accept()


1. andThen()方法:用于组合两个 BiConsumer 实例,形成一个新的 BiConsumer 实例,该实例按顺序执行这两个操作。

public class BiConsumerExample {

    public static void main(String[] args) {
        // 第一个操作
        BiConsumer<String, Integer> printNameAndAge = (name, age) -> {
            System.out.println("Name: " + name + ", Age: " + age);
        };
        
        // 第二个操作
        BiConsumer<String, Integer> printNameLength = (name, age) -> {
            System.out.println("Name Length: " + name.length());
        };
        
        // 使用组合后的 BiConsumer 执行操作
        BiConsumer combined = printNameAndAge.andThen(printNameLength);
        
        combined.accept("John", 25);
    }

}

打印结果

Name: John, Age: 25
Name Length: 4

在上述示例中,我们分别创建了两个 BiConsumer 实例 biConsumer1 和 biConsumer2。然后,使用 andThen() 方法将这两个实例组合成一个新的 BiConsumer 实例 combinedBiConsumer。

组合后的 combinedBiConsumer 将先执行 biConsumer1 的操作,再执行 biConsumer2 的操作。



2. accept()方法:用于接受参数并执行操作。

public class BiConsumerExample {
    public static void main(String[] args) {
        BiConsumer<String, Integer> biConsumer = (str, num) -> {
            System.out.println("String: " + str);
            System.out.println("Integer: " + num);
        };
        String str = "Hello";
        int num = 5;
        biConsumer.accept(str, num);
    }
}

打印结果

String: Hello
Integer: 5

在上述示例中,我们创建了一个 BiConsumer<String, Integer> 实例 biConsumer,它接受一个字符串和一个整数作为参数。在 accept() 方法中,我们打印了传入的字符串和整数。

使用 biConsumer.accept(str, num) 的方式,我们将字符串 "Hello" 和整数 5 传递给 biConsumer 实例来执行操作。


今夜有点儿凉
40 声望3 粉丝

今夜有点儿凉,乌云遮住了月亮。