Optional Class
What is the Optional Class?
- Introduced in Java 8, the
Optionalclass helps handle null values gracefully, avoidingNullPointerException.
- Avoid Null Checks: Reduces explicit null checks.
- Functional Style: Supports
map(),filter(), andifPresent(). - Immutability: Values cannot be modified after creation.
- Use as a return type for methods that may return null.
- Avoid for fields, parameters, or collections to reduce overhead.
-
Empty Optional: Represents no value.
-
With a Value: Wraps a non-null value.
-
With Nullable Value: Allows null values.
-
isPresent(): Checks if a value exists. -
ifPresent(Consumer): Executes code if a value exists. -
orElse(T): Returns the value or a default. -
orElseGet(Supplier): Returns the value or invokes a supplier. -
orElseThrow(Supplier): Throws an exception if no value exists. -
map(Function): Transforms the value if present. -
filter(Predicate): Filters the value based on a condition.
import java.util.Optional;
public class Main {
public static void main(String[] args) {
Optional<String> optional = Optional.ofNullable(getValue());
optional.ifPresent(value -> System.out.println("Value: " + value));
String result = optional.orElse("Default Value");
System.out.println("Result: " + result);
optional.map(String::toUpperCase)
.ifPresent(System.out::println);
}
private static String getValue() {
return null; // Simulates a method that may return null
}
}