The Supplier is a class that was added in Java 8 in the java.util package with is a functional inference, that takes in no input and returns a value.
Supplier.java@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
Let's take a look at some examples:
Example 1: Hello World!
import java.util.function.Supplier;
public class SupplierHelloWorld {
public static void main(String[] args) {
Supplier<String> supplier = () -> "Hello, world!";
String result = supplier.get();
System.out.println(result);
}
}
Example 2: Random Number Supplier
import java.util.Random;
import java.util.function.Supplier;
public class RandomNumberSupplier {
public static void main(String[] args) {
Supplier<Integer> randomNumberSupplier = () -> new Random().nextInt(500);
int randNo = randomNumberSupplier.get();
System.out.println("Random Number: " + randNo);
}
}
Example 3: Current Date Supplier
import java.time.LocalDateTime;
import java.util.function.Supplier;
public class DateTimeSupplier {
public static void main(String[] args) {
Supplier<LocalDateTime> dateTimeSupplier = LocalDateTime::now;
LocalDateTime currentDateTime = dateTimeSupplier.get();
System.out.println("Current Date and Time: " + currentDateTime);
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!