Java 8 Supplier Functional Interface Examples


The Supplier is a class that was added in Java 8 in the java.util package with is a functional inference, that takes in no input and returns a value.

Supplier.java
@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

Let's take a look at some examples:


Example 1: Hello World!
import java.util.function.Supplier;

public class SupplierHelloWorld {

    public static void main(String[] args) {
        Supplier<String> supplier = () -> "Hello, world!";
        String result = supplier.get();
        System.out.println(result);
    }

}

Hello, world!


Example 2: Random Number Supplier
import java.util.Random;
import java.util.function.Supplier;

public class RandomNumberSupplier {

    public static void main(String[] args) {

        Supplier<Integer> randomNumberSupplier = () -> new Random().nextInt(500);
        int randNo = randomNumberSupplier.get();
        System.out.println("Random Number: " + randNo);

    }

}

Random Number: 44


Example 3: Current Date Supplier
import java.time.LocalDateTime;
import java.util.function.Supplier;

public class DateTimeSupplier {

    public static void main(String[] args) {
        Supplier<LocalDateTime> dateTimeSupplier = LocalDateTime::now;
        LocalDateTime currentDateTime = dateTimeSupplier.get();
        System.out.println("Current Date and Time: " + currentDateTime);
    }

}

Current Date and Time: 24-06-2023 11:44:47 CDT

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap