Java Supplier Functional Interface Example

In Java 8, Supplier is a functional interface and that represents a supplier of results.
Java 8 provides predefined functional interfaces to deal with functional programming by using lambda and method references.
In this example, we demonstrate the usage of Supplier predefined functional interfaces.

Java Supplier Functional Interface Example

Create a Person class, this Person class is used to demonstrate Supplier functional Interface example.
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
Here is an example of a Supplier interface:
import java.util.function.Supplier;

public class SuppliersExample {

   public static void main(String[] args) {
  
       Supplier<Person> supplier = () -> { 
           return new Person("Ramesh", 30 );
       };
  
       Person p = supplier.get();
       System.out.println("Person Detail:" + p.getName() + ", " + p.getAge());
   }
}
Output:
Person Detail: Ramesh, 30

Reference


Comments