如何在 Java 中使用 lambda 和方法引用來實現 IntToLongFunction?


IntToLongFunction java.util.function包中的內建函式式介面。此函式式介面接受一個Int 值引數併產生一個long 值結果。IntToLongFunction 介面可以用作lambda 表示式方法 引用的賦值目標。它只包含一個抽象方法:applyAsLong()

語法

@FunctionalInterface
interface IntToLongFunction {
 long applyAsLong(int value);
}

Lambda 表示式的示例

import java.util.function.IntToLongFunction;

public class IntToLongFunctionLambdaTest {
   public static void main(String args[]) {
      IntToLongFunction getLong = intVal -> {      // lambda expression
         long longVal = intVal;
         return longVal;
      };
   
      int input = 40;
      long result = getLong.applyAsLong(input);
      System.out.println("The long value is: " + result);

      input = 75;
      System.out.println("The long value is: " + getLong.applyAsLong(input));

      input = 90;
      System.out.println("The long value is: " + getLong.applyAsLong(input));
   }
}

輸出

The long valus is: 40
The long valus is: 75
The long valus is: 90


方法引用的示例

import java.util.function.IntToLongFunction;

public class IntToLongFunctionMethodRefTest {
   public static void main(String args[]) {
      IntToLongFunction result = IntToLongFunctionMethodRefTest::convertIntToLong;   // method reference
      System.out.println(result.applyAsLong(75));
      System.out.println(result.applyAsLong(45));
   }
   static Long convertIntToLong(int value) {
      return value / 10L;
   }
}

輸出

7
4

更新於: 2020 年 7 月 15 日

122 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.