CodeBlanks Logo Icon CodeBlanks

Supplier<T>

Learn supplier functions with Supplier<T>.

The Supplier<T> interface

Supplier<T> is a factory function that takes no parameter and produces a T value. Its single abstract method is get. It is used to defer value production (lazy evaluation).

Example: Supplier<String> greeting = () -> "Hello";. Then greeting.get() returns "Hello". Supplier is ideal for an expensive value that should only be computed when needed; production does not happen until get is called.

Laziness with Supplier

The most powerful feature of Supplier is its laziness. Nothing is computed until get is called. This is the standard way to do expensive work only when truly needed.

Example: Supplier<List<String>> data = () -> loadFromDisk(). Here loadFromDisk runs only when data.get() is called. You see the same pattern in Optional.orElseGet and Stream.generate; both take a Supplier and produce values lazily.

Practice Produce a value with Supplier

Define a Supplier<String> that uses the lambda () -> "Hello". Print the result of get() with System.out.println.

Starter code

Main.java
import java.util.function.Supplier;

// Define a value-producing Supplier
// Produce the value with get
// Print the result

Sample solution

Main.java
import java.util.function.Supplier;

public class SupplierExample {
    public static void main(String[] args) {
        Supplier<String> greeting = () -> "Hello";
        System.out.println(greeting.get());
    }
}

Expected output

Hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the Supplier call

Question
Supplier<String> greeting = () -> "Merhaba";
String result = greeting.____();
Answer
Supplier<String> greeting = () -> "Merhaba";
String result = greeting.get();

Explanation: get is Supplier's call method.

2 Match the Supplier concepts

Term Meaning
Supplier<T> Produces a value
get Call method
No parameter Supplier's trait
T get() Signature

3 Which interface returns a value without taking a parameter?

  • Function<T,R>
  • Consumer<T>
  • Predicate<T>
  • Supplier<T> Correct answer

Explanation: Supplier<T> takes no parameter and returns T.

All lessons in Advanced