Java 8 Supplier example

Previous
Next

In this post, we are going to see about java 8 Supplier interface.
Supplier is functional interface which does not take any argument and produces result of type T.It has a functional method called T get() As Supplier is functional interface, so it can be used as assignment target for lambda expressions.

Here is source code of Java 8 supplier interface.

Java 8 Supplier example

Lets use supplier 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:

Arpit

Let’s create another example using custom class Student.We will use supplier to supply new Student object.

Now lets create Supplier object which will be used to supply new Student object.

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

Student [id=1, name=Arpit, gender=M, age=19]

Use of supplier in Stream’s generate method

If you observe signature of Stream’s generate method, you will notice that it takes supplier as argument.

Stream's generate method returns an infinite sequential stream where supplier generates each element.
Let’s say you want to generate 5 random numbers between 0 to 10.

Output:

8
3
5
2
2

As you want see we have used supplier as () -> new Random().nextInt(10) to generate random numbers. limit(5) is used to limit the stream to 5 elements only and also used Java 8 foreach loop to print elements of the Stream.
That’s all about Java 8 Supplier example.

Previous
Next

One Response

  1. jack December 31, 2016

Add Comment