J'ai appris à écrire une représentation lambda comme FunctionalInterface . Donc, pour ajouter deux entiers I utilisés:
BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
System.out.println(biFunction.apply(10, 60));
Donne - moi la sortie 70 . Mais si je l' écris comme cela
BinaryOperator<Integer, Integer, Integer> binaryOperator = (a, b) -> a + b;
Je reçois une erreur disant
Mauvais nombre d'arguments de type: 3; requis: 1
Est -ce pas BinaryOperator
un enfant BinaryFunction
? Comment puis-je améliorer?
BinaryOperator
Depuis les BinaryOperator
travaux sur un seul type d'opérandes et le résultat . à savoir BinaryOperator<T>
.
N'est pas BinaryOperator un enfant de BinaryFunction?
Oui. BinaryOperator
fait extends BiFunction
. Mais faire noter les états de documentation (mine de formatage):
C'est une spécialisation de
BiFunction
pour le cas où les opérandes et le résultat sont tous du même type .
La représentation complète est aussi:
BinaryOperator<T> extends BiFunction<T,T,T>
par conséquent, votre code doit travailler avec
BinaryOperator<Integer> binaryOperator = (a, b) -> a + b;
System.out.println(binaryOperator.apply(10, 60));
IntBinaryOperator
Si vous êtes censé avoir affaire à deux entiers primitifs comme actuellement dans votre exemple ( ajouter deux entiers j'ai utilisé ), vous pouvez utiliser la IntBinaryOperator
FunctionalInterface comme
IntBinaryOperator intBinaryOperator = (a, b) -> a + b;
System.out.println(intBinaryOperator.applyAsInt(10, 60));
Représente une opération sur deux
int
opérandes -Évaluées et produire un résultat d'une valeur int. Ceci est la spécialisation de type primitif deBinaryOperator
pourint
.
J'utilise Integer, puis-je utiliser IntBinaryOperator
Oui, vous pouvez toujours l' utiliser mais remarquez la représentation duIntBinaryOperator
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);
pourrait vous engager une surcharge de unboxing first
et second
de primitives puis autoboxing la somme en sortie à result
de type Integer
.
Note : Soyez prudent d'utiliser des valeurs nulles de sécurité pour leInteger
bien ou bien vous finirez probablement avecNullPointerException
.