Supplier Functional Interface Example

Java 8 added a new functional interface named “Supplier”. The purpose of this interface is to supply instances.

I will be explaining using the below example. In the example I have want of list of employees. I will separate the logic behind employee instance creation and adding to list.

The employee instance will be created by Supplier interface implementation. By calling get on the implementation I get the employee instance and it to the list.


package Function;

public class Employee {
    public String name;
    public boolean terminated;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public boolean isTerminated() {
        return terminated;
    public void setTerminated(boolean terminated) {
        this.terminated = terminated;
    public String toString() {
        StringBuilder sb = new StringBuilder();
        return sb.toString();

Supplier Interface Implementation

package Function;

import java.util.function.Supplier;

public class EmployeeSupplier implements Supplier {
    private int i = 0;
    public Employee get() {
        Employee employee = new Employee();
        return employee;

According to the above code the implementation implements only one method named get which returns employee instance.

The get method doesn’t accept anything as a parameter.

Main code

1  package Function;
3  import java.util.ArrayList;
4  import java.util.List;
6  public class SupplierDemo {
7   public static void main(String[] args) {
8       List list = new ArrayList();
10      EmployeeSupplier employeeSupplier = new EmployeeSupplier();
12      for(int i = 0; i < 5; i++) {
13          Employee employee = employeeSupplier.get();
14          list.add(employee);
15      }
17      for(Employee employee : list) {
18          System.out.println(employee);
19      }
20  }
21 }

At line 13 I call get of the functional interface implementation to get the employee instance.

At line 14 I add them to the list.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s