Functionの結果をBiConsumerで実行する(2)

昨日書いた、
Functionの結果をBiConsumerで実行する - Oboe吹きプログラマの黙示録
もっとよく考えてみれば、、
ApplyBiConsumer のリストではく、
続けてafterオペレーションを実行する andThen を使うのが良さそうである。

BiConsumer継承の方法では、

import java.util.function.BiConsumer;
import java.util.function.Function;

@FunctionalInterface
public interface ApplyBiConsumer<T, U> extends BiConsumer<T, U>{
   static <T, U, V> ApplyBiConsumer<T, U> of(Function<T, V> f, BiConsumer<U, V> b) {
       return (t,u)->{
          b.accept(u, f.apply(t));
       };
   }
}
import lombok.Data;
@Data
public class Foo{
   private String name;
   private int id;
   private LocalDate birthday;
}

import lombok.Data;
@Data
public class Person{
   private String name;
   private int id;
   private LocalDate birthday;
   private String info;
}

andThen を使って、、、

Foo foo;       // Foo のインスタンス
Person person; // Person のインスタンス

// Foo の方に値セット済

ApplyBiConsumer.of(Foo::getName, Person::setName)
.andThen(ApplyBiConsumer.of(Foo::getId, Person::setId))
.andThen(ApplyBiConsumer.of(Foo::getBirthday, Person::setBirthday))
.accept(foo, person);

BiConsumer継承ではなく、andThen と同じ and と短い名称にすれば、、

import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Function;

@FunctionalInterface
public interface ApplyBiConsumer<T, U> {
   void accept(T t, U u);

   static <T, U, V> ApplyBiConsumer<T, U> of(Function<T, V> f, BiConsumer<U, V> b) {
       return (t,u)->{
          b.accept(u, f.apply(t));
       };
   }
   default ApplyBiConsumer<T, U> and(ApplyBiConsumer<? super T, ? super U> after) {
      Objects.requireNonNull(after);
      return (l, r) -> {
          accept(l, r);
          after.accept(l, r);
      };
   }
}

継承でない方では、、

Foo foo;       // Foo のインスタンス
Person person; // Person のインスタンス

// Foo の方に値セット済

ApplyBiConsumer.of(Foo::getName, Person::setName)
.and(ApplyBiConsumer.of(Foo::getId, Person::setId))
.and(ApplyBiConsumer.of(Foo::getBirthday, Person::setBirthday))
.accept(foo, person);

最終的には、後日投稿の以下がベスト
Functionの結果をBiConsumerで実行する(3) - Oboe吹きプログラマの黙示録