✅ 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:
Interface | Input | Output | Use Case Example |
---|---|---|---|
Supplier<T> | — | T | () -> "Hello" |
BooleanSupplier | — | boolean | () -> Math.random() > 0.5 |
IntSupplier | — | int | () -> new Random().nextInt() |
LongSupplier | — | long | () -> System.nanoTime() |
DoubleSupplier | — | double | () -> Math.random() |