如何在 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

更新于:2020 年 7 月 13 日

788 次浏览

开启你的 职业生涯

完成本课程获得认证

开始
广告
© . All rights reserved.