Skip to content
Advertisement

When and why would you use Java’s Supplier and Consumer interfaces?

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.

Advertisement

Answer

This is Supplier:

JavaScript

This is Consumer:

JavaScript

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:

JavaScript

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.

JavaScript
Advertisement