第3部分 函数式接口(Consumer)

发布: (2026年3月3日 GMT+8 16:04)
2 分钟阅读
原文: Dev.to

Source: Dev.to

Consumer

Consumerjava.util.function 中的函数式接口。
它表示一个接受一个输入并且不返回结果的操作。

核心方法

void accept(T t)

Consumer 中的额外方法

  • andThen(Consumer after) – 将两个 Consumer 链接在一起。
    当前的 Consumer 先执行,随后执行 afterConsumer

示例

Consumer print = s -> System.out.println(s);
Consumer printUpper = s -> System.out.println(s.toUpperCase());

Consumer combined = print.andThen(printUpper);

combined.accept("hello");
// Output:
// hello
// HELLO

专用的 Consumer

BiConsumer

表示接受两个输入并且不返回结果的操作。

BiConsumer printNameAge =
    (name, age) -> System.out.println(name + " is " + age + " years old");

printNameAge.accept("Ravi", 25);
// Output: Ravi is 25 years old

原始类型 Consumer 接口

在处理原始类型时,专用的 consumer 接口可以避免装箱/拆箱的开销。

IntConsumer

接受 int 类型的 consumer。

IntConsumer printSquare = n -> System.out.println(n * n);
printSquare.accept(5); // Output: 25

LongConsumer

接受 long 类型的 consumer。

LongConsumer printHalf = l -> System.out.println(l / 2);
printHalf.accept(100L); // Output: 50

DoubleConsumer

接受 double 类型的 consumer。

DoubleConsumer printDoubleValue = d -> System.out.println(d * 2);
printDoubleValue.accept(3.5); // Output: 7.0

期待再见……我们将在下一篇精彩的博客中相会!

0 浏览
Back to Blog

相关文章

阅读更多 »