如何在 Java 中在 lambda 表示式中使用 IntSupplier?
IntSupplier 是一個在 "java.util.function" 包中定義的功能介面。此介面表示一個操作,該操作不帶引數,並返回 int 型別的結果。IntSupplier 介面只有一個方法,getAsInt() ,並返回一個結果。此功能介面可以用作 lambda 表示式 或 方法 引用的賦值目標。
語法
@FunctionalInterface public interface IntSupplier { int getAsInt(); }
示例
import java.util.function.IntSupplier; public class IntSupplierTest { public static void main(String[] args) { IntSupplier intSupplier1 = () -> Integer.MAX_VALUE; // lamba expression System.out.println("The maximum value of an Integer is: " + intSupplier1.getAsInt()); IntSupplier intSupplier2 = () -> Integer.MIN_VALUE; System.out.println("The minimum value of an Integer is: " + intSupplier2.getAsInt()); int a = 10, b = 20; IntSupplier intSupplier3 = () -> a*b; System.out.println("The multiplication of a and b is: " + intSupplier3.getAsInt()); } }
輸出
The maximum value of an Integer is: 2147483647 The minimum value of an Integer is: -2147483648 The multiplication of a and b is: 200
廣告