问题描述
作为一名学习Java的非Java程序员,我正在阅读 Supplier
和 Consumer
接口。我无法围绕他们的用法和意义。您何时以及为何使用这些界面?有人可以给我一个简单的非专业人士的例子......我发现Doc的例子不够简洁,无法理解。
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.
推荐答案
这是供应商:
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 it's return value). Whereas, a consumer is a method that consumes some value (as in method argument), and does some operations on them.
那些将转变为类似的东西:
Those will transform to something like these:
// 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);
至于用法,最基本的例子是:方法。它需要一个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 8供应商&消费者对外行的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!