
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Supplier Interface in Lambda Expression in Java
A Supplier<T> interface is a pre-defined interface that represents the supplier of results. It is instantiated using lambda expression or method reference or default constructor. The functional method of a Supplier<T> interface is the get() method. This interface belongs to java.util.function package.
Syntax
@FunctionalInterface public interface Supplier<T>
In the below program, we can use the Supplier interface in a lambda expression. The get() method only returns a value and doesn't accept any argument, so a lambda expression having an empty argument part.
Example
import java.util.*; import java.util.function.*; public class SupplierTest { public static void main(String args[]) { Supplier<String> supplier1 = () -> "TutorialsPoint"; // lambda expression System.out.println(supplier1.get()); Supplier<Integer> supplier2 = () -> 7; // lambda expression System.out.println(supplier2.get()); Person p = new Person("Raja"); Person p1 = get(() -> p); Person p2 = get(() -> p); System.out.println(p1.equals(p2)); } public static Person get(Supplier<Person> supplier) { return supplier.get(); } } // Person class class Person { public Person(String name) { System.out.println(name); } }
Output
TutorialsPoint 7 Raja true
Advertisements