私はいくつかのようラムダ表現を書くことを学んでいた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つの整数を追加します)、あなたは利用することができIntBinaryOperator
FunctionalInterfaceとして
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);
あなたのオーバーヘッド被るボックス化解除 first
とsecond
プリミティブにして、オートボクシングへの出力として合計をresult
タイプしInteger
。
注:使用するように注意してくださいヌルセーフ値のためにInteger
あなたはおそらくで終わるでしょうけれどもか、他をNullPointerException
。