Java 8: java.util.function の TriFunction (および kin) はどこにありますか? または、代替手段は何ですか? 質問する

Java 8: java.util.function の TriFunction (および kin) はどこにありますか? または、代替手段は何ですか? 質問する

java.util.function.BiFunction が見つかったので、次のように実行できます。

BiFunction<Integer, Integer, Integer> f = (x, y) -> { return 0; };

それでも十分ではなく、TriFunction が必要な場合はどうすればいいでしょうか? TriFunction は存在しません!

TriFunction<Integer, Integer, Integer, Integer> f = (x, y, z) -> { return 0; };

独自の TriFunction を定義できることはわかっているので、それを標準ライブラリに含めない理由を理解しようとしているだけだということを付け加えておくべきだと思います。

ベストアンサー1

TriFunction が必要な場合は、次のようにします。

@FunctionalInterface
interface TriFunction<A,B,C,R> {

    R apply(A a, B b, C c);

    default <V> TriFunction<A, B, C, V> andThen(
                                Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (A a, B b, C c) -> after.apply(apply(a, b, c));
    }
}

次の小さなプログラムは、それがどのように使用されるかを示しています。結果の型は、最後のジェネリック型パラメータとして指定されることに注意してください。

  public class Main {

    public static void main(String[] args) {
        BiFunction<Integer, Long, String> bi = (x,y) -> ""+x+","+y;
        TriFunction<Boolean, Integer, Long, String> tri = (x,y,z) -> ""+x+","+y+","+z;


        System.out.println(bi.apply(1, 2L)); //1,2
        System.out.println(tri.apply(false, 1, 2L)); //false,1,2

        tri = tri.andThen(s -> "["+s+"]");
        System.out.println(tri.apply(true,2,3L)); //[true,2,3]
    }
  }

java.util.*または で TriFunction が実際に使用されていたら、定義されていたと思いますjava.lang.*。ただし、引数が 22 を超えることは決してありません ;-) つまり、コレクションのストリームを可能にするすべての新しいコードでは、メソッド パラメーターとして TriFunction は必要ありません。そのため、含まれませんでした。

アップデート

完全性を期し、別の回答(カリー化に関連)の破壊関数の説明に従って、追加のインターフェースなしで TriFunction をエミュレートする方法を次に示します。

Function<Integer, Function<Integer, UnaryOperator<Integer>>> tri1 = a -> b -> c -> a + b + c;
System.out.println(tri1.apply(1).apply(2).apply(3)); //prints 6

もちろん、他の方法で関数を組み合わせることも可能です。例:

BiFunction<Integer, Integer, UnaryOperator<Integer>> tri2 = (a, b) -> c -> a + b + c;
System.out.println(tri2.apply(1, 2).apply(3)); //prints 6
//partial function can be, of course, extracted this way
UnaryOperator partial = tri2.apply(1,2); //this is partial, eq to c -> 1 + 2 + c;
System.out.println(partial.apply(4)); //prints 7
System.out.println(partial.apply(5)); //prints 8

カリー化はラムダ式を超える関数型プログラミングをサポートする言語であれば自然に行えますが、Java はこのように構築されておらず、実現可能ではあるものの、コードの保守が難しく、場合によっては読みにくくなります。ただし、練習としては非常に役立ち、部分関数がコード内で適切な位置を占める場合もあります。

おすすめ記事