Quelle FunctionalInterface dois-je utiliser?

mains:

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 BinaryOperatorun enfant BinaryFunction? Comment puis-je améliorer?

aussi:

BinaryOperator

Depuis les BinaryOperatortravaux sur un seul type d'opérandes et le résultat . à savoir BinaryOperator<T>.

N'est pas BinaryOperator un enfant de BinaryFunction?

Oui. BinaryOperatorfait extends BiFunction. Mais faire noter les états de documentation (mine de formatage):

C'est une spécialisation de BiFunctionpour 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 IntBinaryOperatorFunctionalInterface comme

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

Représente une opération sur deux intopérandes -Évaluées et produire un résultat d'une valeur int. Ceci est la spécialisation de type primitif de BinaryOperatorpour int.


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 secondde primitives puis autoboxing la somme en sortie à resultde type Integer.

Note : Soyez prudent d'utiliser des valeurs nulles de sécurité pour leIntegerbien ou bien vous finirez probablement avecNullPointerException.

Je suppose que tu aimes

Origine http://43.154.161.224:23101/article/api/json?id=167321&siteId=1
conseillé
Classement