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.

Employee


package Function;

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

Supplier Interface Implementation


package Function;

import java.util.function.Supplier;

public class EmployeeSupplier implements Supplier {
    private int i = 0;
    
    @Override
    public Employee get() {
        Employee employee = new Employee();
        employee.setName("name"+i);
        i++;
        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;
2  
3  import java.util.ArrayList;
4  import java.util.List;
5  
6  public class SupplierDemo {
7   public static void main(String[] args) {
8       List list = new ArrayList();
9       
10      EmployeeSupplier employeeSupplier = new EmployeeSupplier();
11      
12      for(int i = 0; i < 5; i++) {
13          Employee employee = employeeSupplier.get();
14          list.add(employee);
15      }
16      
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.

Output

name0:false
name1:false
name2:false
name3:false
name4:false

Leave a Reply