如何使用 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