如何在 Java 中使用 lambda 和方法引用實現 ToIntFunction?\n


ToIntFunction<T> java.util.function 包中定義的內建函式介面。此函式介面需要一個引數作為輸入,並生成整數結果。可將其用作lambda 表示式 方法 引用 的賦值目標。ToIntFunction 介面僅包含一個方法applyAsInt()。此方法對給定引數執行操作並返回整數結果。

語法

@FunctionalInterface
public interface ToIntFunction {
   int applyAsInt(T value);
}

在以下示例中,我們可以透過使用 lambda 表示式和方法引用來實現ToIntFunction<T>。

示例

import java.util.function.ToIntFunction;
import java.time.LocalDate;

public class ToIntFunctionInterfaceTest {
   public static void main(String[] args) {
      ToIntFunction<Integer> lambdaObj = value -> value * 25;   // using lambda expression
      System.out.println("The result is: " + lambdaObj.applyAsInt(10));

      ToIntFunction<String> lenFn = String::length;   // using method reference
      System.out.println("The length of a String is: " + lenFn.applyAsInt("tutorialspoint"));
   }  
}

輸出

The result is: 250
The length of a String is: 14

更新於: 2020-7-13

595 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.