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

The get() Method: Retrieving Values

Calling get() on a Supplier to obtain the produced value, and understanding that it can be called multiple times.

The get() Method: Retrieving Values

You'll learn how to call get() on a Supplier to retrieve values and understand its reusable nature.

What Does get() Do?

The get() method is the single abstract method of the Supplier<T> interface. When you call get() on a Supplier, it executes the supplier's logic and returns a value of type T. Think of it like pressing a button on a vending machine—each press delivers a product according to the machine's programming.

Basic Usage

To retrieve a value from a Supplier, simply invoke get():

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

Calling get() Multiple Times

Here's the important part: you can call get() as many times as you need. Each call executes the supplier's logic again:

Supplier<Double> randomValue = () -> Math.random();

double first = randomValue.get();   // e.g., 0.234
double second = randomValue.get();  // e.g., 0.891 (different value)
double third = randomValue.get();   // e.g., 0.456 (different again)

Each get() call may return the same value or different values, depending on the supplier's implementation. A supplier that returns a constant will always give the same result, while one that generates values will produce fresh results each time.

The Value of Reusability

This multiple-call capability makes Supplier perfect for lazy evaluation, factory patterns, and scenarios where you need values on demand rather than computed upfront.

Key Takeaway: The get() method retrieves a value from a Supplier and can be called multiple times—each invocation executes the supplier's logic, potentially producing different results depending on the implementation.