如何使用 lambda 在 Java 中實現 LongConsumer?
LongConsumer 是 java.util.function 包中一個內建的函式介面。此介面可以接收單個長整型值作為輸入,並且不生成任何輸出。它還可以用作lambda 表示式或方法 引用的賦值目標,幷包含一個抽象方法:accept()和一個預設方法:andThen()。
語法
@FunctionalInterface public interface LongConsumer
示例 1
import java.util.function.LongConsumer;
public class LongConsumerLambdaTest {
public static void main(String[] args) {
LongConsumer displayNextVal = l-> { // lambda expression
System.out.println("Display the next value to input : "+l);
System.out.println(l+1);
};
LongConsumer displayPrevVal = l-> { // lambda expression
System.out.println("Display the previous value to input : "+l);
System.out.println(l-1);
};
LongConsumer displayPrevAndNextVal = displayNextVal.andThen(displayPrevVal);
displayPrevAndNextVal.accept(1000);
}
}輸出
Display the next value to input : 1000 1001 Display the previous value to input : 1000 999
示例 2
import java.util.Arrays;
import java.util.function.LongConsumer;
public class LongConsumerTest {
public static void main(String[] args) {
long[] numbers = {13l, 3l, 6l, 1l, 8l};
LongConsumer longCon = l -> System.out.print(l + " ");
Arrays.stream(numbers).forEach(longCon);
}
}輸出
13 3 6 1 8
廣告
資料結構
網路
關係型資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP