Site icon JavaGoal

Supplier interface in Java

The supplier interface is defined in the java.util.function package. It contains one abstract method which is known as get() method. This interface returns the result of Type T. The supplier interface has only one method that supplies the data, unlike the consumer interface it doesn’t consume any data. In this post, we will see what is supplier functional interface in detail and discuss it with example.

The Supplier interface is useful where you want to get an object of type T. It does not take any object as input but produces a value of type T. This interface is used in a lambda expression and method reference where the user wants to return an object. This interface is only used to get/supply the data to another function.

@FunctionalInterface
public interface Supplier<T> 
{
    // Body of Interface
}

Where T, The type of object which you want to get from Supplier.
T get( ) method: This method is used to produce an object of type T. Its return type is T.

T get() method

How to use the supplier functional interface?

First of all, we will see how to use the Predicate interface without a lambda expression.

import java.util.function.Supplier;

public class ExampleOfSupplierWithoutLambda 
{
	public static void main(String[] args) 
	{
		Supplier<String> supplier = new Supplier<String>() 
		{
			@Override
			public String get() 
			{
				return "Hello";
			}
		};
		System.out.println(supplier.get());
	}
}

Output: Hello

Now, we will see how you can use the Supplier interface with a lambda expression:

 import java.util.function.Supplier;

public class ExampleOfSupplierWithLambda 
{
	public static void main(String[] args) 
	{
		Supplier<String> supplier = () -> "Hello";
		System.out.println(supplier.get());
	}
}

Output: Hello

Let’s discuss Supplier with user-defined class

public class Student 
{
	int rollNo;
	String className;
	String name;
	
	public Student(int rollNo, String className, String name) 
	{
		this.rollNo = rollNo;
		this.className = className;
		this.name = name;
	}
	public int getRollNo() 
	{
		return rollNo;
	}
	public void setRollNo(int rollNo) 
	{
		this.rollNo = rollNo;
	}
	public String getClassName() 
	{
		return className;
	}
	public void setClassName(String className) 
	{
		this.className = className;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}
import java.util.function.Supplier;

public class ExampleOfSupplierForStudent 
{
	public static void main(String[] args) 
	{
		Supplier<Student> supplier = () -> new Student(5, "MCA", "Ram");
		System.out.println("Student name:"+supplier.get().getName());
		
	}
}

Output: Student name:Ram

Exit mobile version