Java IntConsumer 接口
最后修改时间:2025 年 4 月 16 日
java.util.function.IntConsumer 接口表示一个操作,该操作接受一个 int 值的参数,并且不返回任何结果。它是一个函数式接口,只有一个抽象方法 accept。
IntConsumer 是 Java 8 中添加的 Java 函数式编程实用程序的一部分。它是 Consumer 针对 int 的原始类型特化。当处理原始 int 值时,这避免了自动装箱的开销。
IntConsumer 接口概述
IntConsumer 接口包含一个抽象方法和一个默认方法。关键方法 accept 对输入执行操作。 andThen 方法允许链接消费者。
@FunctionalInterface
public interface IntConsumer {
void accept(int value);
default IntConsumer andThen(IntConsumer after);
}
上面的代码显示了 IntConsumer 接口的结构。它使用 @FunctionalInterface 进行注解,以表明其单个抽象方法的性质。该接口设计用于对 int 值进行副作用操作。
IntConsumer 的基本用法
使用 IntConsumer 的最简单方法是使用 lambda 表达式。我们在 accept 方法中定义对输入 int 值做什么。该示例打印数字。
package com.zetcode;
import java.util.function.IntConsumer;
public class Main {
public static void main(String[] args) {
// Define a consumer that prints the number
IntConsumer printNumber = n -> System.out.println("Number: " + n);
// Use the consumer
printNumber.accept(5);
printNumber.accept(10);
// Consumer that squares the number and prints
IntConsumer squareAndPrint = n -> System.out.println(n + " squared: " + n * n);
squareAndPrint.accept(4);
}
}
此示例演示了使用 lambda 表达式的 IntConsumer 基本用法。printNumber 消费者只是打印输入值。squareAndPrint 消费者在打印之前执行计算。消费者对于副作用很有用。
使用 andThen 链接消费者
andThen 方法允许链接消费者,其中每个消费者按顺序处理相同的输入值。这使得模块化副作用成为可能。
package com.zetcode;
import java.util.function.IntConsumer;
public class Main {
public static void main(String[] args) {
// First consumer prints the number
IntConsumer print = n -> System.out.println("Original: " + n);
// Second consumer prints the number doubled
IntConsumer printDouble = n -> System.out.println("Doubled: " + n * 2);
// Chain the consumers
IntConsumer combined = print.andThen(printDouble);
// Execute the chain
combined.accept(7);
combined.accept(12);
}
}
此示例显示了使用 andThen 链接消费者。相同的输入值(7 和 12)流经两个消费者。每个消费者独立执行其操作。保证了执行顺序。
IntConsumer 与流
IntConsumer 通常与 IntStream 一起使用,用于处理原始 int 值。forEach 方法接受一个 IntConsumer 来处理每个元素。
package com.zetcode;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// Create a range of numbers
IntStream numbers = IntStream.rangeClosed(1, 5);
// Define a consumer that processes each number
numbers.forEach(n -> {
System.out.println("Processing: " + n);
System.out.println("Square root: " + Math.sqrt(n));
});
// Another example with method reference
IntStream.of(10, 20, 30).forEach(System.out::println);
}
}
此示例演示了 IntConsumer 与 IntStream 的用法。传递给 forEach 的 lambda 是一个 IntConsumer,它处理每个流元素。当操作与现有方法匹配时,也可以使用方法引用。
有状态的 IntConsumer
虽然通常不鼓励,但 IntConsumer 可以维护状态。此示例显示了一个消费者,该消费者跟踪和报告它处理的数字的统计信息。
package com.zetcode;
import java.util.function.IntConsumer;
public class Main {
public static void main(String[] args) {
// Stateful consumer that tracks statistics
class StatsConsumer implements IntConsumer {
private int count = 0;
private int sum = 0;
private int min = Integer.MAX_VALUE;
private int max = Integer.MIN_VALUE;
@Override
public void accept(int value) {
count++;
sum += value;
min = Math.min(min, value);
max = Math.max(max, value);
}
public void printStats() {
System.out.println("Count: " + count);
System.out.println("Sum: " + sum);
System.out.println("Min: " + (count > 0 ? min : "N/A"));
System.out.println("Max: " + (count > 0 ? max : "N/A"));
}
}
StatsConsumer stats = new StatsConsumer();
IntStream.of(5, 10, 2, 8, 3).forEach(stats);
stats.printStats();
}
}
此示例显示了有状态的 IntConsumer 实现。StatsConsumer 跟踪已处理值的计数、总和、最小值和最大值。虽然是函数式的,但在并行流中使用这种有状态的消费者应该小心。
IntConsumer 在集合中
IntConsumer 可以与包含原始 int 值的集合一起使用。此示例演示了使用消费者处理 int 数组。
package com.zetcode;
import java.util.Arrays;
import java.util.function.IntConsumer;
public class Main {
public static void main(String[] args) {
int[] temperatures = {22, 25, 19, 30, 17};
// Consumer that checks for extreme temperatures
IntConsumer tempChecker = temp -> {
if (temp > 28) {
System.out.println("Heat warning: " + temp + "°C");
} else if (temp < 20) {
System.out.println("Cold warning: " + temp + "°C");
}
};
// Process all temperatures
Arrays.stream(temperatures).forEach(tempChecker);
// Another example with array modification
int[] squares = new int[temperatures.length];
IntConsumer squareStorer = i -> squares[i] = temperatures[i] * temperatures[i];
for (int i = 0; i < temperatures.length; i++) {
squareStorer.accept(i);
}
System.out.println("Squares: " + Arrays.toString(squares));
}
}
此示例显示了 IntConsumer 与数组的用法。tempChecker 分析每个温度值。squareStorer 演示了消费者如何处理数组索引。消费者提供了对原始值的灵活处理。
将 IntConsumer 与其他函数式接口结合使用
IntConsumer 可以与其他函数式接口(如 IntPredicate 或 IntFunction)结合使用,以创建更复杂的数据处理流程。
package com.zetcode;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
public class Main {
public static void main(String[] args) {
// Predicate to check for even numbers
IntPredicate isEven = n -> n % 2 == 0;
// Consumer for even numbers
IntConsumer evenProcessor = n -> System.out.println("Even: " + n);
// Consumer for odd numbers
IntConsumer oddProcessor = n -> System.out.println("Odd: " + n);
// Process numbers with conditional logic
IntStream.range(1, 6).forEach(n -> {
if (isEven.test(n)) {
evenProcessor.accept(n);
} else {
oddProcessor.accept(n);
}
});
// Another example with IntFunction and IntConsumer
java.util.function.IntFunction intToString = Integer::toString;
IntConsumer printHex = n -> System.out.println("Hex: " + Integer.toHexString(n));
IntStream.of(10, 20, 30)
.mapToObj(intToString)
.forEach(s -> System.out.println("String: " + s));
IntStream.of(10, 20, 30).forEach(printHex);
}
}
此示例显示了 IntConsumer 与其他函数式接口一起工作。第一部分演示了使用 IntPredicate 的条件处理。第二部分显示了在流管道中与 IntFunction 的集成。这种组合实现了强大的数据处理模式。
来源
在本文中,我们介绍了 Java IntConsumer 接口的基本方法和特性。理解这些概念对于在 Java 函数式编程中有效地处理原始 int 值至关重要。
作者
列出所有Java教程。