Learnitweb

Supplier interface in Java

Supplier is a functional interface introduced in Java 8 and available in java.util.function package.

This interface has functional method get(). Supplier does not take a argument and returns a result every time it is called.

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

Here, T represents the type of the result.

The supplier can be used in cases where there is no input but an output is expected. Since Supplier is a functional interface, hence it can be used as the assignment target for a lambda expression or a method reference.

Supplier example

In the following example, we have created supplier which returns a java.util.Date object every time it is called.

import java.util.Date;
import java.util.function.Supplier;

public class SupplierExample {
	public static void main(String[] args) {
		Supplier<Date> s = () -> new Date();
		
		System.out.println(s.get());
	}
}

Output

Fri Oct 09 17:11:19 IST 2020

Supplier example to get object

In the following example, we have created a class Employee with two properties: id and name. Supplier return the new object of the Employee whenever it is called.

import java.util.function.Supplier;

class Employee {
	private int id;
	private String name;
	
	public Employee(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}
}

public class SupplierExample {
	public static void main(String[] args) {
		Supplier<Employee> supplier = () -> new Employee(1, "John");
		
		Employee emp = supplier.get();
		System.out.println(emp);
	}
}

Output

Employee [id=1, name=John]