Java Supplier

Introduction

In Java, the Supplier interface is a functional interface that represents a supplier of results. It is part of the java.util.function package and is commonly used to generate or supply values without taking any input.

Table of Contents

  1. What is Supplier?
  2. Methods and Syntax
  3. Examples of Supplier
  4. Real-World Use Case
  5. Conclusion

1. What is Supplier?

Supplier is a functional interface that provides a result when called. It is useful in scenarios where a value needs to be generated or fetched on demand without any input parameters.

2. Methods and Syntax

The main method in the Supplier interface is:

  • T get(): Gets a result.

Syntax

Supplier<T> supplier = () -> {
    // logic to return a value
    return result;
};

3. Examples of Supplier

Example 1: Returning a Constant String

import java.util.function.Supplier;

public class ConstantStringSupplier {
    public static void main(String[] args) {
        // Define a Supplier that returns a constant string
        Supplier<String> stringSupplier = () -> "Hello, World!";

        String result = stringSupplier.get();
        System.out.println(result);
    }
}

Output:

Hello, World!

Example 2: Generating a Random Number

import java.util.function.Supplier;
import java.util.Random;

public class RandomNumberSupplier {
    public static void main(String[] args) {
        // Define a Supplier that returns a random number
        Supplier<Integer> randomSupplier = () -> new Random().nextInt(100);

        int result = randomSupplier.get();
        System.out.println("Random Number: " + result);
    }
}

Output:

Random Number: [Random number between 0 and 99]

4. Real-World Use Case: Fetching Current Time

In applications, Supplier can be used to fetch the current system time.

import java.util.function.Supplier;
import java.time.LocalTime;

public class CurrentTimeSupplier {
    public static void main(String[] args) {
        // Define a Supplier to fetch the current time
        Supplier<LocalTime> timeSupplier = LocalTime::now;

        LocalTime currentTime = timeSupplier.get();
        System.out.println("Current Time: " + currentTime);
    }
}

Output:

Current Time: [Current time in HH:MM:SS format]

Conclusion

The Supplier interface is a versatile tool in Java for providing values without any input parameters. It is particularly beneficial in scenarios like generating constant values, random numbers, or fetching current data. Using Supplier can help create modular and reusable code, especially in functional programming contexts.

Comments