Java : DoubleSupplier with Examples

DoubleSupplier (Java SE 21 & JDK 21) with Examples.
You will find code examples on most DoubleSupplier methods.


Summary

Represents a supplier of double-valued results. This is the double-producing primitive specialization of Supplier.

Class diagram

final var opt1 = DoubleStream.of(0.123, 4.56).findFirst();
final var opt2 = DoubleStream.empty().findFirst();

final var other = new DoubleSupplier() {
    @Override
    public double getAsDouble() {
        return 0.789;
    }
};

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

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

Methods

double getAsDouble ()

Gets a result.

final var opt1 = DoubleStream.of(0.123, 4.56).findFirst();
final var opt2 = DoubleStream.empty().findFirst();

final var other = new DoubleSupplier() {
    @Override
    public double getAsDouble() {
        return 0.789;
    }
};

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

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

Related posts

To top of page