Java IntSupplier 接口
最后修改时间:2025 年 4 月 16 日
java.util.function.IntSupplier 接口表示一个提供整数值结果的供应器。它是一个函数式接口,具有单个抽象方法 getAsInt。IntSupplier 不接受任何参数,但会产生一个 int 值。
IntSupplier 是 Java 8 中添加的 Java 函数式编程实用程序的一部分。它是 Supplier 的一个原始特化,用于 int 值。这避免了在使用原始整数时发生的自动装箱开销。
IntSupplier 接口概述
IntSupplier 接口包含一个抽象方法。关键方法 getAsInt 返回一个整数值,无需任何输入。此接口中没有默认方法或静态方法。
@FunctionalInterface
public interface IntSupplier {
int getAsInt();
}
上面的代码显示了 IntSupplier 的简单结构。它使用 @FunctionalInterface 注解来表明其单个抽象方法的性质。该接口设计用于高效的原始 int 操作。
IntSupplier 的基本用法
使用 IntSupplier 的最简单方法是使用 lambda 表达式。我们在 getAsInt 方法中定义如何生成整数值。该示例显示了随机数生成。
package com.zetcode;
import java.util.function.IntSupplier;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
// Define a supplier that generates random numbers
IntSupplier randomSupplier = () -> ThreadLocalRandom.current().nextInt(1, 101);
// Get values from supplier
System.out.println("Random number: " + randomSupplier.getAsInt());
System.out.println("Random number: " + randomSupplier.getAsInt());
// Supplier with constant value
IntSupplier constantSupplier = () -> 42;
System.out.println("Constant value: " + constantSupplier.getAsInt());
}
}
此示例演示了使用 lambda 表达式的基本 IntSupplier 用法。randomSupplier 生成 1-100 之间的数字。每次调用 getAsInt 都会产生一个新值。constantSupplier 始终返回相同的值。
IntSupplier 与方法引用
当使用与接口签名匹配的方法时,方法引用提供了一种创建 IntSupplier 实例的简洁方法。此示例使用类方法作为供应器。
package com.zetcode;
import java.util.function.IntSupplier;
public class Main {
private static int getCounter() {
return Counter.getCount();
}
public static void main(String[] args) {
// Using method reference as IntSupplier
IntSupplier counterSupplier = Main::getCounter;
System.out.println("Counter value: " + counterSupplier.getAsInt());
System.out.println("Counter value: " + counterSupplier.getAsInt());
}
}
class Counter {
private static int count = 0;
public static int getCount() {
return ++count;
}
}
此示例显示了通过方法引用创建的 IntSupplier。getCounter 方法与 IntSupplier 的函数式签名匹配。每次调用 getAsInt 都会调用该方法,返回递增的计数器值。
IntSupplier 用于惰性求值
IntSupplier 适用于惰性求值场景,其中值生成成本很高。计算只发生在调用 getAsInt 时,而不是创建供应器时。
package com.zetcode;
import java.util.function.IntSupplier;
public class Main {
public static void main(String[] args) {
// Expensive computation wrapped in supplier
IntSupplier expensiveValue = () -> {
System.out.println("Performing expensive calculation...");
try {
Thread.sleep(1000); // Simulate long computation
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return 12345;
};
System.out.println("Supplier created, computation not done yet");
System.out.println("Value: " + expensiveValue.getAsInt());
}
}
此示例演示了使用 IntSupplier 的惰性求值。昂贵的计算被推迟到调用 getAsInt 时。供应器可以在不触发计算的情况下传递,直到需要时。
IntSupplier 在流生成中
IntSupplier 可与 Stream.generate 一起使用,以创建无限的整数值流。这对于生成序列或随机数很有用。
package com.zetcode;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// Fibonacci sequence supplier
IntSupplier fibSupplier = new IntSupplier() {
private int previous = 0;
private int current = 1;
@Override
public int getAsInt() {
int next = previous + current;
previous = current;
current = next;
return previous;
}
};
// Generate stream of Fibonacci numbers
IntStream.generate(fibSupplier)
.limit(10)
.forEach(System.out::println);
}
}
此示例显示了 IntSupplier 生成斐波那契数。供应器在调用之间维护状态。我们使用它与 IntStream.generate 一起创建无限流,限制为前 10 个数字。
将 IntSupplier 与其他函数式接口组合
IntSupplier 可以与其他函数式接口组合以创建更复杂的行为。此示例显示了与 IntConsumer 的组合。
package com.zetcode;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
public class Main {
public static void processValues(IntSupplier supplier, IntConsumer consumer, int count) {
for (int i = 0; i < count; i++) {
consumer.accept(supplier.getAsInt());
}
}
public static void main(String[] args) {
// Supplier for squares
IntSupplier squareSupplier = new IntSupplier() {
private int n = 1;
@Override
public int getAsInt() {
int result = n * n;
n++;
return result;
}
};
// Consumer to print with formatting
IntConsumer formattedPrinter = value ->
System.out.printf("Processed value: %,d%n", value);
// Process 5 values
processValues(squareSupplier, formattedPrinter, 5);
}
}
此示例演示了将 IntSupplier 与 IntConsumer 组合。processValues 方法接受两个接口,生成和使用值。squareSupplier 产生平方数,而 consumer 格式化输出。
IntSupplier 用于配置值
IntSupplier 适用于提供可能在调用之间更改的可配置值。供应器可以封装用于值确定的逻辑。
package com.zetcode;
import java.util.function.IntSupplier;
public class Main {
private static class ConfigManager {
private static int threshold = 10;
public static IntSupplier getThresholdSupplier() {
return () -> {
// Simulate dynamic configuration
threshold = (threshold * 2) % 50;
return threshold;
};
}
}
public static void main(String[] args) {
IntSupplier thresholdSupplier = ConfigManager.getThresholdSupplier();
for (int i = 0; i < 5; i++) {
System.out.println("Current threshold: " + thresholdSupplier.getAsInt());
}
}
}
此示例显示了 IntSupplier 提供动态配置值。阈值在每次请求时都会更改。供应器封装了用于确定当前阈值的逻辑。
来源
在本文中,我们涵盖了 Java IntSupplier 接口的基本方法和特性。理解这些概念对于 Java 应用程序中的函数式编程和高效的原始操作至关重要。
作者
列出所有Java教程。