Java 8 Supplier example

In this post, we are going to see about java 8 Supplier interface.
Consumer is single argument functional interface like Predicate and used to get objects. As Supplier is functional interface, so it  can be used as assignment target for lambda expressions.
It has a functional method called get()
Lets use Consumer interface to print String:

It is simple use of supplier interface to get String object. When you run above program, you will get below output:

Passing Supplier to Stream API methods:

Supplier can be passed as argument to Stream ‘s method. In this example, we will pass Supplier to  map method of Stream API.
Lets say you have student class as below:

Now lets create Consumer object in main class and pass it to forEach method of list:

When you run above program, you will get below output:

One Response

  1. jack December 31, 2016

Add Comment