o7planning

Java Supplier Tutorial with Examples

  1. Supplier
  2. Supplier Usage
  3. Supplier + Method reference
  4. Supplier + Constructor reference

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

Show More