BiConsumer定义了两个泛型类型T和R,分别做为accept()方法的参数类型,BiConsumer支持2个参数。
自定义IBiConsumer类
- @Data
- public class IBiConsumer
{ -
- private final BiConsumer
biConsumer; -
- // 初始化biConsumer
- public IBiConsumer(BiConsumer
biConsumer) { - this.biConsumer = biConsumer;
- }
-
- public void consume(T t, R r) {
- System.out.println("这里可以进行一系列的操作");
- biConsumer.accept(t, r);
- }
- }
测试
- public static void main(String[] args) {
- IBiConsumer
biConsumer = new IBiConsumer<>((k,v) -> { - System.out.println("此处是对两个参数的打印, k = " + k + " v = " + v);
- });
- biConsumer.consume("vvv","kkk");
- }
- //这里可以进行一系列的操作
- //此处是对两个参数的打印, k = 这是一段测试内容 v = 没错,这还是一段测试内容
super T, ? super U> super表示下限的类型,extends 表示上限的类型,参数1 至少为T类型或者为T类型的父类,参数2为U类型或者U类型的父类。andThen方法表示会继承当前BiConsumer继续调用下一个BiConsumer里的accept()方法。
自定义IBiConsumer类
- @Data
- public class IBiConsumer
{ -
- private final BiConsumer
biConsumer; -
- private IBiConsumer
next; -
- // 初始化biConsumer
- public IBiConsumer(BiConsumer
biConsumer) { - this.biConsumer = biConsumer;
- }
-
- public void consume(T t, R r) {
- //当前
- BiConsumer
chainConsumer = this.biConsumer; - while (this.next != null) {
- //将会把所有的要执行的任务合成到chainConsumer这一个对象中
- chainConsumer = chainConsumer.andThen(this.next.biConsumer);
- next = next.next;
- }
- //统一执行
- chainConsumer.accept(t, r);
- }
-
- public void addLast(BiConsumer
biConsumer) { - // 遍历链表到表尾
- IBiConsumer
current = this; - while (current.next != null) {
- current = current.next;
- }
- current.next = new IBiConsumer<>(biConsumer);
- }
- }
测试
- public static void main(String[] args) {
- IBiConsumer
biConsumer = new IBiConsumer<>((k,v) -> { - System.out.println("此处是对两个参数的打印, k = " + k + " v = " + v);
- });
-
- biConsumer.addLast((k,v) -> {
- System.out.println(k + v);
- });
-
- biConsumer.addLast((k,v) -> {
- System.out.println(k + v + "ccc");
- });
-
- biConsumer.addLast((k,v) -> {
- System.out.println(k + v + "ccc" + "ddd");
- });
-
-
- biConsumer.consume("aaa","bbb");
- }
- //aaabbb
- //aaabbbccc
- //aaabbbcccddd