Java.util。函数.IntBinaryOperator 接口与示例
IntBinaryOperator接口是在Java 8 中引入的。它表示对两个 int 值的操作,并将结果作为 int 值返回。它是一个函数式接口,因此可以用作 lambda 表达式或方法引用。它主要用于需要从用户封装操作的情况。
方法
- applyAsInt() :此函数采用两个 int 值,执行所需的操作并将结果作为 int 返回。
public int applyAsInt(int val1, int val2)
将 IntBinaryOperator 接口演示为 lambda 表达式的示例。
// Java program to demonstrate IntBinaryOperator
import java.util.function.IntBinaryOperator;
public class IntBinaryOperatorDemo {
public static void main(String[] args)
{
// Binary operator defined to divide
// factorial of two numbers
IntBinaryOperator binaryOperator = (x, y) ->
{
int fact1 = 1;
for (int i = 2; i <= x; i++) {
fact1 *= i;
}
int fact2 = 1;
for (int i = 2; i <= y; i++) {
fact2 *= i;
}
return fact1 / fact2;
};
System.out.println("5! divided by 7! = "
+ binaryOperator.applyAsInt(5, 7));
System.out.println("7! divided by 5! = "
+ binaryOperator.applyAsInt(7, 5));
}
}
输出:
5! divided by 7! = 0
7! divided by 5! = 42
参考: https: Java/util/函数/IntBinaryOperator.html