Learn about Supplier Functional Interface in Java

Supplier is a Functional Interface, so it only contains an abstract method as follows:

This interface simply returns the value in the context that is being used by the get() method.

For example, we have the following list:

Now that I want to use the Supplier interface to get the value of each element in the list and print out to the console, I will write a method like this:

And now we can use this method:

In the above code, instead of using the Consumer interface, I used the print() method with the Supplier interface parameter, which is the value of each element in the list.

Result:

Learn about Supplier Functional Interface in Java

Like the Consumer interface, here are some variations of the Supplier interface:

  • Interface IntSupplier: The getAsInt() method returns the Integer value.
  • Interface DoubleSupplier: with the getAsDouble() method returns a Double value.
  • LongSupplier interface: with the getAsLong() method returns a Long value.
  • Interface BooleanSupplier: The getAsBoolean() method returns the Integer value.

Add Comment