Java : Supplier with Examples

Supplier (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Supplier<T> methods.


Summary

Represents a supplier of results.

Class diagram

final var opt1 = Stream.of("abcd", "efgh").findFirst();
final var opt2 = Stream.<String>empty().findFirst();

final var other = new Supplier<String>() {
    @Override
    public String get() {
        return "XYZ";
    }
};

System.out.println(opt1.orElseGet(other)); // abcd
System.out.println(opt2.orElseGet(other)); // XYZ
// An example with a lambda expression.
final var opt = Stream.empty().findFirst();

System.out.println(opt.orElseGet(() -> "XYZ")); // XYZ

Methods

T get ()

Gets a result.

final var supplier = new Supplier<String>() {
    @Override
    public String get() {
        return "abcd";
    }
};

System.out.println(supplier.get()); // abcd
final var supplier = new Supplier<String>() {
    int count = 0;

    @Override
    public String get() {
        count++;
        return "a".repeat(count);
    }
};

final var stream = Stream.generate(supplier);

final var ret = stream.limit(4).toList();
System.out.println(ret); // [a, aa, aaa, aaaa]
// An example with a lambda expression.
final var opt = Stream.empty().findFirst();

System.out.println(opt.orElseGet(() -> "XYZ")); // XYZ

Related posts

To top of page