Java.Java8.What are the functional interfaces Supplier, BooleanSupplier, DoubleSupplier, IntSupplier, and LongSupplier?

✅ 1. Supplier<T>

Package: java.util.function

  • Represents a function that supplies a result of type T, with no input.
@FunctionalInterface
public interface Supplier<T> {
    T get();
}

🧠 Example:

Supplier<String> greetingSupplier = () -> "Hello, world!";
System.out.println(greetingSupplier.get()); // Output: Hello, world!

🔧 Use Cases:

  • Lazily generating values.
  • Supplying default values.
  • Used in places like Optional.orElseGet():
String name = Optional.ofNullable(null).orElseGet(() -> "Default");

✅ 2. BooleanSupplier

  • Specialization for boolean primitives.
  • Avoids boxing.
@FunctionalInterface
public interface BooleanSupplier {
    boolean getAsBoolean();
}

🧠 Example:

BooleanSupplier randomBool = () -> Math.random() > 0.5;
System.out.println(randomBool.getAsBoolean()); // true or false

✅ 3. IntSupplier

Supplies an int value.

@FunctionalInterface
public interface IntSupplier {
    int getAsInt();
}

🧠 Example:

IntSupplier randomInt = () -> (int)(Math.random() * 100);
System.out.println(randomInt.getAsInt()); // e.g. 42

✅ 4. LongSupplier

Supplies a long value.

@FunctionalInterface
public interface LongSupplier {
    long getAsLong();
}

Example

LongSupplier currentTime = () -> System.currentTimeMillis();
System.out.println(currentTime.getAsLong());

✅ 5. DoubleSupplier

Supplies a double value.

@FunctionalInterface
public interface DoubleSupplier {
    double getAsDouble();
}

🧠 Example:

DoubleSupplier pi = () -> Math.PI;
System.out.println(pi.getAsDouble()); // 3.141592653...

🔄 Summary Table:

InterfaceInputOutputUse Case Example
Supplier<T>T() -> "Hello"
BooleanSupplierboolean() -> Math.random() > 0.5
IntSupplierint() -> new Random().nextInt()
LongSupplierlong() -> System.nanoTime()
DoubleSupplierdouble() -> Math.random()
This entry was posted in Без рубрики. Bookmark the permalink.