Java : LongSupplier with Examples

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


Summary

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

Class diagram

final var opt1 = LongStream.of(123, 456).findFirst();
final var opt2 = LongStream.empty().findFirst();

final var other = new LongSupplier() {
    @Override
    public long getAsLong() {
        return 789;
    }
};

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

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

Methods

long getAsLong ()

Gets a result.

final var opt1 = LongStream.of(123, 456).findFirst();
final var opt2 = LongStream.empty().findFirst();

final var other = new LongSupplier() {
    @Override
    public long getAsLong() {
        return 789;
    }
};

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

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

Related posts

To top of page