Java Optional Methods Descriptions Examples
Java Optional Methods Descriptions Examples
1. empty()
- Description: Returns an empty Optional instance.
- Example:
Optional<String> opt = Optional.empty();
2. of(T value)
- Description: Returns an Optional with the specified non-null value.
- Example:
Optional<String> opt = Optional.of("Hello");
3. ofNullable(T value)
- Description: Returns an Optional with the specified value, or empty if null.
- Example:
Optional<String> opt = Optional.ofNullable(null);
4. isPresent()
- Description: Returns true if the value is present.
- Example:
if (opt.isPresent()) {
System.out.println(opt.get());
}
5. ifPresent(Consumer action)
- Description: Performs the action if a value is present.
- Example:
opt.ifPresent(System.out::println);
6. get()
- Description: Returns the value if present, else throws exception.
- Example:
String value = opt.get();
7. orElse(T other)
- Description: Returns value if present, else other.
- Example:
String result = opt.orElse("Default");
8. orElseGet(Supplier)
- Description: Returns value if present, else generated by supplier.
- Example:
String result = opt.orElseGet(() -> "Generated");
9. orElseThrow(Supplier)
- Description: Returns value if present, else throws exception.
- Example:
String result = opt.orElseThrow(() -> new IllegalArgumentException("No value"));
10. map(Function)
- Description: Transforms the value if present.
- Example:
Optional<Integer> length = opt.map(String::length);
11. flatMap(Function)
- Description: Similar to map, avoids nested Optionals.
- Example:
Optional<String> flat = opt.flatMap(val -> Optional.of(val.toUpperCase()));
12. filter(Predicate)
- Description: Keeps value only if predicate matches.
- Example:
Optional<String> filtered = opt.filter(val -> val.length() > 3);