如何使用 Java 中的 Lambda 和方法引用来实现 LongBinaryOperator?
LongBinaryOperator 是 java.util.function 包中的函数式接口的一部分。此函数式接口期望 long 类型的 两个参数作为输入,并生成一个 long 类型的结果。LongBinaryOperator 接口可以用作 lambda 表达式 或 方法 引用的赋值目标。它只包含一个抽象方法,applyAsLong()。
句法
@FunctionalInterface
public interface LongBinaryOperator {
long applyAsLong(long left, long right)
}Lambda 表达式的示例
import java.util.function.LongBinaryOperator;
public class LongBinaryOperatorTest1 {
public static void main(String[] args) {
LongBinaryOperator multiply = (a,b) -> { // lambda expression
return a*b;
};
long a = 10;
long b = 20;
long result = multiply.applyAsLong(a,b);
System.out.println("Multiplication of a and b: " + result);
a = 20;
b = 30;
System.out.println("Multiplication of a and b: " + multiply.applyAsLong(a,b));
a = 30;
b = 40;
System.out.println("Multiplication of a and b: " + multiply.applyAsLong(a,b));
}
}输出
Multiplication of a and b: 200 Multiplication of a and b: 600 Multiplication of a and b: 1200
方法引用的示例
import java.util.function.LongBinaryOperator;
public class LongBinaryOperatorTest2 {
public static void main(String[] args) {
LongBinaryOperatorTest2 instance = new LongBinaryOperatorTest2();
LongBinaryOperator test = instance::print; // method reference
System.out.println("The sum of l1 and l2: " + test.applyAsLong(50, 70));
}
long print(long l1, long l2) {
return l1+l2;
}
}输出
The sum of l1 and l2: 120
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP