Supplier

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Supplier<T> is a built-in functional interface in the java.util.function package.
  • It takes no arguments and returns a result of type T.
  • It is primarily used for lazy generation, creating objects, or providing default values.
  • Its abstract method is T get().

Concept

A Supplier is the exact opposite of a Consumer. It doesn’t take any input, but it supplies output.

Suppliers are particularly valuable for Lazy Evaluation. If generating a value is computationally expensive, you might not want to generate it immediately. Instead, you can pass a Supplier to a method. The method will only call supplier.get() to execute the expensive code if and when the value is actually needed.

Examples

import java.util.Optional;
import java.util.function.Supplier;

public class SupplierExample {
    public static void main(String[] args) {
        
        // A supplier that generates a random number
        Supplier<Double> randomSupplier = () -> Math.random();
        
        // The lambda is not executed until we call get()
        System.out.println(randomSupplier.get()); 
        
        
        // --- Real-world usage: Lazy Evaluation with Optional ---
        Optional<String> emptyOptional = Optional.empty();
        
        // orElseGet expects a Supplier.
        // The lambda () -> "Default Value" is ONLY executed because the Optional is empty.
        String result = emptyOptional.orElseGet(() -> "Default Value");
        System.out.println(result);
        
        
        // Another example: Generating objects
        Supplier<User> userFactory = () -> new User();
        User u = userFactory.get();
    }
}

class User {}

Interview Questions

Q: What is the difference between Optional.orElse() and Optional.orElseGet()?
A: orElse(T value) takes a concrete value. Even if the Optional is full and doesn’t need the default value, the concrete value is evaluated and created before orElse is called (Eager evaluation).
orElseGet(Supplier<? extends T> supplier) takes a Supplier. The code inside the supplier is never executed unless the Optional is actually empty (Lazy evaluation). If creating the default value requires a database call, you absolutely must use orElseGet() to avoid unnecessary DB calls.

Q: Are there primitive versions of Supplier?
A: Yes. To avoid the performance overhead of Autoboxing, Java provides primitive-specific suppliers: IntSupplier (returns int via getAsInt()), DoubleSupplier (returns double via getAsDouble()), and BooleanSupplier (returns boolean via getAsBoolean()).