In this article, we will discuss pre-defined Functional Interface in Java 1.8 version which performs some operation (processing) and returns value after processing but doesn’t take any input arguments i.e.; Supplier Functional Interface
1. Supplier Functional Interface:
- This Functional Interface has one abstract method called T get(); which
- Step 1 :- doesn’t take any input argument
- Step 2 :- performs some operation or processes
- Step 3 :- And return result of any data-type
- Below is the Supplier Functional interface containing get(); method
package java.util.function;
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
2. Examples for Supplier Functional Interface:
Example 1 – program to get current timestamp
package net.bench.resources.supplier.example;
import java.sql.Timestamp;
import java.util.function.Supplier;
public class GetCurrentTimestamp {
public static void main(String[] args) {
// lambda expression to get current Timestamp
Supplier<Timestamp> s = () -> new Timestamp(System.currentTimeMillis());
// invoke above Supplier FI to get print current Timestamp
System.out.println(s.get());
}
}
Output:
2020-04-25 05:37:27.185
Example 2 – program to generate high security password of 8 digits for Customer login to Bank portal
package net.bench.resources.supplier.example;
import java.util.function.Supplier;
public class GenerateHighSecurityPassword {
public static void main(String[] args) {
// lambda expression to generate high security password using Supplier
Supplier<StringBuffer> s = () -> {
// local variable
StringBuffer password = new StringBuffer();
// iterate through 8 times to generate unique number
for(int i=0; i<8; i++) {
// append each ransom integer digit to StringBuffer
password.append((int)(Math.random() * 10));
}
// finally return password
return password;
};
// invoke above Supplier FI to print password for customer login
System.out.println(s.get());
}
}
Output:
55212896
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html
- https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
- https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
Happy Coding !!
Happy Learning !!