Sobes.tech
Junior

What is a Supplier in Java?

sobes.tech AI

Answer from AI

Supplier<T> is a functional interface in Java 8, defined in the java.util.function package. It represents a provider of results of type T.

Its main purpose is deferred computation. Supplier takes no arguments and has a single abstract method get(), which returns a value of type T.

// Example of using Supplier
import java.util.function.Supplier;

public class SupplierExample {

    public static void main(String[] args) {
        // Creating a Supplier that returns the string "Hello, world!"
        Supplier<String> greetingSupplier = () -> "Hello, world!";

        // Getting the value from the Supplier
        String greeting = greetingSupplier.get();
        System.out.println(greeting); // Output: Hello, world!

        // Example of deferred computation
        Supplier<Double> randomValueSupplier = () -> Math.random();

        // The value is computed only when get() is called
        System.out.println(randomValueSupplier.get());
        System.out.println(randomValueSupplier.get()); // Will be a different random number
    }
}

Applications:

  • Deferred initialization: Resources or values are computed only when they are actually needed.
  • Value generation: Used to create new objects or values on demand.
  • Conditional logging: Log messages can be generated only if the logging level permits.
  • Method parameters: Can be used as a method parameter type, allowing to pass logic for value generation.

Advantages:

  • Performance: Avoids unnecessary computations, especially if they are costly or their result may not be needed.
  • Code clarity: Allows separating data generation logic from its usage.
  • Lambda expressions: Easily used with lambda expressions and method references.

Unlike other functional interfaces like Consumer (accepts an argument, returns nothing) or Function (accepts an argument, returns a value), Supplier simply provides a value without input data.