Course contentsShow
← Java
Lesson 1665 of 2,87035. Functional InterfacesFree lesson

What is Supplier<T> and When to Use It

Understanding Supplier as a function that takes no arguments and produces a value of type T.

What is Supplier<T> and When to Use It

You'll learn: What the Supplier<T> functional interface is and when to use functions that provide values without taking input.

The Core Idea

A Supplier<T> is a functional interface that represents a function taking no arguments and producing a result of type T. Think of it as a vending machine for values—you don't put anything in, but you get something out when you call it.

The interface has a single abstract method:

T get()

Understanding the Pattern

Unlike Function<T, R> (which transforms input to output) or Consumer<T> (which consumes input), a Supplier is all about generation or provision. It supplies values on demand.

Common scenarios:

  • Lazy initialization – Create expensive objects only when needed
  • Factory methods – Generate new instances
  • Default values – Provide fallback values
  • Random generation – Produce random or computed values

The Analogy

Imagine asking a bakery: "Give me a fresh croissant." You don't provide ingredients (no input), you just get the product (output). That's a Supplier in action.

Basic Pattern

Supplier<String> greeting = () -> "Hello";
String message = greeting.get();  // "Hello"

Supplier<Double> randomValue = Math::random;
Double number = randomValue.get();  // Random value each call

When to Use It

Use Supplier<T> when you need to defer computation or generate values on demand without passing parameters. It's particularly useful in Stream operations, Optional defaults, and lazy evaluation scenarios.

Key Takeaway: Supplier<T> is a no-argument function that produces values of type T via its get() method, perfect for lazy initialization and value generation.