Java Supplier Tutorial with Examples
1. Supplier
No ADS
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
No ADS
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
No ADS
Java Basic
- Data Types in java
- Java PhantomReference Tutorial with Examples
- JDK Javadoc in CHM format
- Java Stream Tutorial with Examples
- Java Predicate Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- Arrays in Java
- JDBC Driver Libraries for different types of database in Java
- Abstract class and Interface in Java
- Java Commons Email Tutorial with Examples
- Install Eclipse
- Bitwise Operations
- Install Eclipse on Ubuntu
- Configuring Eclipse to use the JDK instead of JRE
- Java Commons Logging Tutorial with Examples
- Java Enums Tutorial with Examples
- Loops in Java
- Java Regular Expressions Tutorial with Examples
- Install Java on Ubuntu
- Quick Learning Java for beginners
- Install Java on Windows
- Comparing and Sorting in Java
- Inheritance and polymorphism in Java
- Java Consumer Tutorial with Examples
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- if else statement in java
- Switch Statement in Java
- Java Supplier Tutorial with Examples
- Java Programming for team using Eclipse and SVN
- Java JDBC Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- What is needed to get started with Java?
- Java Aspect Oriented Programming with AspectJ (AOP)
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java Compression and Decompression Tutorial with Examples
- Java Reflection Tutorial with Examples
- Install OpenJDK on Ubuntu
- Java String.format() and printf() methods
- History of Java and the difference between Oracle JDK and OpenJDK
- Introduction to the Raspberry Pi
- Java Socket Programming Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java WeakReference Tutorial with Examples
- Java Commons IO Tutorial with Examples
- History of bits and bytes in computer science
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java SoftReference Tutorial with Examples
- Syntax and new features in Java 8
- Java Annotations Tutorial with Examples
- Java Function Tutorial with Examples
- Access modifiers in Java
- Java BiFunction Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Functional Interface Tutorial with Examples
- Java BiPredicate Tutorial with Examples
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