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

更新於: 2020-07-13

130 次瀏覽

開啟你的職業生涯 生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.