Issue
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.
Solution
This is Supplier:
public Integer getInteger() {
return new Random().nextInt();
}
This is Consumer:
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.
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);
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);
Answered By - Rohit Jain
Answer Checked By - Marilyn (JavaFixing Volunteer)