私はどちらFunctionalInterfaceを使用する必要がありますか?

ハンズ:

私はいくつかのようラムダ表現を書くことを学んでいたFunctionalInterfaceだから、私が使用した2つの整数を追加します。

BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
System.out.println(biFunction.apply(10, 60));

私に出力できます70しかし、私はこのようにそれを書いた場合

BinaryOperator<Integer, Integer, Integer> binaryOperator = (a, b) -> a + b;

私はというエラーを取得します

型引数の数が間違って:3。必要:1

ではないBinaryOperatorの子BinaryFunctionどのように私はそれを改善するのですか?

また:

BinaryOperator

以降BinaryOperatorの作品のオペランドと結果のシングルタイプすなわちBinaryOperator<T>

BinaryFunctionのBinaryOperator子ではないですか?

はい。BinaryOperatorありませんextends BiFunctionしかし、ドキュメントの状態を(私のフォーマット)に注意を実行します。

これは、特殊であるBiFunction場合のオペランドと結果は、すべてのある同じタイプ

完全な表現は通りです:

BinaryOperator<T> extends BiFunction<T,T,T>

したがって、あなたのコードはで動作するもの

BinaryOperator<Integer> binaryOperator = (a, b) -> a + b;
System.out.println(binaryOperator.apply(10, 60));

IntBinaryOperator

あなたはあなたの例では、現在のような2つのプリミティブ整数を扱うことになっている場合は(私が使用した2つの整数を追加します)、あなたは利用することができIntBinaryOperatorFunctionalInterfaceとして

IntBinaryOperator intBinaryOperator = (a, b) -> a + b;
System.out.println(intBinaryOperator.applyAsInt(10, 60));

2時の動作を表しint-valuedオペランドと整数値の結果を生成します。これは、プリミティブ型の専門BinaryOperatorためint


私はまだIntBinaryOperatorを使用することができ、整数を使用しています

はい、あなたはまだそれを使用することができますが、表現に気付きますIntBinaryOperator

Integer first = 10;
Integer second = 60;
IntBinaryOperator intBinaryOperator = new IntBinaryOperator() {
    @Override
    public int applyAsInt(int a, int b) {
        return Integer.sum(a, b);
    }
};
Integer result = intBinaryOperator.applyAsInt(first, second); 

あなたのオーバーヘッド被るボックス化解除 firstsecondプリミティブにして、オートボクシングへの出力として合計をresultタイプしInteger

:使用するように注意してくださいヌルセーフ値のためにIntegerあなたはおそらくで終わるでしょうけれどもか、他をNullPointerException

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=167320&siteId=1