Java Supplier Tutorial with Examples
1. Supplier
In Java 8, Supplier is a simple functional interface, which is represents an operator that provides a value for each call. Supplier has only one get() method and has no default method.
Supplier
@FunctionalInterface
public interface Supplier<T> {
T get();
}
There are a few other similar functional interfaces that provide primitive values: IntSupplier, DoubleSupplier, LongSupplier, BooleanSupplier:
IntSupplier int getAsInt();
DoubleSupplier double getAsDouble();
LongSupplier long getAsLong();
BooleanSupplier boolean getAsBoolean();
- IntSupplier
- DoubleSupplier
- LongSupplier
- BooleanSupplier
Example: Using Supplier to return a random number for each call.
SupplierEx1.java
package org.o7planning.ex;
import java.util.function.Supplier;
public class SupplierEx1 {
public static void main(String[] args) {
Supplier<Double> random = () -> Math.random();
System.out.println("Random value: " + random.get());
System.out.println("Random value: " + random.get());
System.out.println("Random value: " + random.get());
}
}
Output:
Random value: 0.5085772031422864
Random value: 0.666568263619468
Random value: 0.18177402871597048
Example: Using Supplier to return the current date:
SupplierEx2.java
package org.o7planning.ex;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Supplier;
public class SupplierEx2 {
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
Supplier<LocalDateTime> s = () -> LocalDateTime.now();
LocalDateTime time = s.get();
System.out.println(time);
Supplier<String> s1 = () -> dtf.format(LocalDateTime.now());
String time2 = s1.get();
System.out.println(time2);
}
}
Output:
2021-02-12T13:31:43.023203
2021-02-12 13:31:43
Example: Using Supplier in static method Stream.generate to print out 5 random numbers:
// Method of java.util.stream.Stream class:
static <T> Stream<T> generate(Supplier<T> s)
SupplierEx3.java
package org.o7planning.ex;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class SupplierEx3 {
public static void main(String[] args) {
// Returns a random integer in range [0,10)
Supplier<Integer> randomNumbersSupp = () -> new Random().nextInt(10);
Stream.generate(randomNumbersSupp)
.limit(5)
.forEach(System.out::println); // .forEach(Consumer)
}
}
Output:
5
5
0
2
0
2. Supplier Usage
Below is a list of methods in java.util package using Supplier:
Modifier and Type | Method and Description |
T | Optional.orElseGet(Supplier<? extends T> other) |
<X extends Throwable>
T | Optional.orElseThrow(Supplier<? extends X> exceptionSupplier) |
<X extends Throwable>
long | OptionalLong.orElseThrow(Supplier<X> exceptionSupplier) |
<X extends Throwable>
double | OptionalDouble.orElseThrow(Supplier<X> exceptionSupplier) |
<X extends Throwable>
int | OptionalInt.orElseThrow(Supplier<X> exceptionSupplier) |
static <T> T | Objects.requireNonNull(T obj, Supplier<String> messageSupplier) |
3. Supplier + Method reference
A method that takes no parameters and returns a value then its reference will be considered a Supplier.
SupplierEx4.java
package org.o7planning.ex;
import java.time.LocalDate;
import java.util.function.Supplier;
public class SupplierEx4 {
public static void main(String[] args) {
Supplier<Integer> s1 = MyUtils::getCurrentYear; // Method reference
System.out.println(s1.get());
Employee employee = new Employee("Tom");
Supplier<String> s2 = employee::getName; // Method reference
System.out.println(s2.get());
}
public static class MyUtils {
public static int getCurrentYear() {
return LocalDate.now().getYear();
}
}
public static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
}
Output:
2021
Tom
4. Supplier + Constructor reference
A Constructor will create a new object. If it has no parameters, its reference is considered a Supplier.
SupplierEx7.java
package org.o7planning.ex;
import java.util.Random;
import java.util.function.Supplier;
public class SupplierEx7 {
public static void main(String[] args) {
Supplier<Random> s = Random::new; // Constructor reference
//
int randomValue = s.get().nextInt(10);
System.out.println("Random Value: " + randomValue);
}
}
Output:
Random Value: 8
Java Basic
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- Java Programming for team using Eclipse and SVN
- Java WeakReference Tutorial with Examples
- Java PhantomReference Tutorial with Examples
- Java Compression and Decompression Tutorial with Examples
- Configuring Eclipse to use the JDK instead of JRE
- Java String.format() and printf() methods
- Syntax and new features in Java 8
- Java Regular Expressions Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- JDBC Driver Libraries for different types of database in Java
- Java JDBC Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Stream Tutorial with Examples
- Java Functional Interface Tutorial with Examples
- Introduction to the Raspberry Pi
- Java Predicate Tutorial with Examples
- Abstract class and Interface in Java
- Access modifiers in Java
- Java Enums Tutorial with Examples
- Java Annotations Tutorial with Examples
- Comparing and Sorting in Java
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java BiPredicate Tutorial with Examples
- Java Consumer Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- What is needed to get started with Java?
- History of Java and the difference between Oracle JDK and OpenJDK
- Install Java on Windows
- Install Java on Ubuntu
- Install OpenJDK on Ubuntu
- Install Eclipse
- Install Eclipse on Ubuntu
- Quick Learning Java for beginners
- History of bits and bytes in computer science
- Data Types in java
- Bitwise Operations
- if else statement in java
- Switch Statement in Java
- Loops in Java
- Arrays in Java
- JDK Javadoc in CHM format
- Inheritance and polymorphism in Java
- Java Function Tutorial with Examples
- Java BiFunction Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- Java Reflection Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Socket Programming Tutorial with Examples
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java Commons IO Tutorial with Examples
- Java Commons Email Tutorial with Examples
- Java Commons Logging Tutorial with Examples
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java SoftReference Tutorial with Examples
- Java Supplier Tutorial with Examples
- Java Aspect Oriented Programming with AspectJ (AOP)
Show More
- Java Servlet/Jsp Tutorials
- Java Collections Framework Tutorials
- Java API for HTML & XML
- Java IO Tutorials
- Java Date Time Tutorials
- Spring Boot Tutorials
- Maven Tutorials
- Gradle Tutorials
- Java Web Services Tutorials
- Java SWT Tutorials
- JavaFX Tutorials
- Java Oracle ADF Tutorials
- Struts2 Framework Tutorials
- Spring Cloud Tutorials