何时以及为何使用 Java 的供应商和消费者接口? [英] When and why would you use Java's Supplier and Consumer interfaces?
问题描述
作为一名学习 Java 的非 Java 程序员,我目前正在阅读有关 Supplier
和 Consumer
接口的内容.我无法理解它们的用法和含义.
As a non-Java programmer learning Java, I am reading about Supplier
and Consumer
interfaces at the moment. And I can't wrap my head around their usage and meaning.
您何时以及为何使用这些接口?有人可以给我一个简单的外行例子吗?
When and why you would use these interfaces? Can someone give me a simple layperson example of this?
我发现文档示例不够简洁,无法理解.
I'm finding the Doc examples not succinct enough for my understanding.
推荐答案
This is Supplier:
This is Supplier:
public Integer getInteger() {
return new Random().nextInt();
}
这是消费者:
public void sum(Integer a, Integer b) {
System.out.println(a + b);
}
因此,通俗地说,供应商是一种返回某些值(如其返回值)的方法.而消费者是一种方法,它消耗一些值(如方法参数),并对它们进行一些操作.
So in layman terms, a supplier is a method that returns some value (as in its return value). Whereas, a consumer is a method that consumes some value (as in method argument), and does some operations on them.
那些会变成这样的:
// new operator itself is a supplier, of the reference to the newly created object
Supplier<List<String>> listSupplier = ArrayList::new;
Consumer<String> printConsumer = a1 -> System.out.println(a1);
BiConsumer<Integer, Integer> sumConsumer = (a1, a2) -> System.out.println(a1 + a2);
至于用法,非常基本的例子是:Stream#forEach(Consumer)
方法.它需要一个消费者,它消耗您正在迭代的流中的元素,并对每个元素执行一些操作.可能打印出来.
As for usage, the very basic example would be: Stream#forEach(Consumer)
method. It takes a Consumer, which consumes the element from the stream you're iterating upon, and performs some action on each of them. Probably print them.
Consumer<String> stringConsumer = (s) -> System.out.println(s.length());
Arrays.asList("ab", "abc", "a", "abcd").stream().forEach(stringConsumer);
这篇关于何时以及为何使用 Java 的供应商和消费者接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!