Optional
in Java 8:
In Java 8,
Optional is a container object introduced in the java.util package. It is used
to represent a value that can either be present (non-null) or absent (null). It
provides a way to avoid NullPointerException (NPE) and improve code readability
when dealing with nullable values.
Key
Characteristics of Optional:
- Avoids Null Checks: Provides methods to
handle nullable values without explicit null checks.
- Immutable: The Optional object is immutable,
meaning its value cannot be changed once set.
- Improves Readability: It reduces boilerplate
code and enhances readability when handling optional or nullable values.
Common
Methods in Optional:
- Creating an Optional:
- Optional.of(T value): Creates an Optional with a
non-null value. Throws NullPointerException if the value is null.
- Optional.ofNullable(T value): Creates an Optional
that can hold a null or non-null value.
- Optional.empty(): Returns an empty Optional.
- Checking for Value:
- isPresent(): Returns true if a value is present,
otherwise false.
- isEmpty(): Returns true if no value is present,
otherwise false.
- Retrieving the Value:
- get(): Returns the value if present; otherwise,
throws NoSuchElementException.
- orElse(T other): Returns the value if present;
otherwise, returns the provided default value.
- orElseGet(Supplier<? extends T> supplier):
Returns the value if present; otherwise, invokes the supplier and returns
its result.
- orElseThrow(Supplier<? extends X>
exceptionSupplier): Returns the value if present; otherwise, throws an
exception provided by the supplier.
- Processing the Value:
- ifPresent(Consumer<? super T> action):
Executes the given action if a value is present.
- map(Function<? super T, ? extends U>
mapper): Applies a mapping function if a value is present and returns a
new Optional.
- flatMap(Function<? super T,
Optional<U>> mapper): Similar to map but avoids nested Optional.
Example Usage:
1. Basic Usage
Optional<String> optional =
Optional.ofNullable("Hello, World!");
if (optional.isPresent()) {
System.out.println(optional.get()); // Output: Hello, World!
} else {
System.out.println("No value present.");
}
2. Using orElse
and ifPresent
Optional<String> optional =
Optional.ofNullable(null);
// Using orElse
String result =
optional.orElse("Default Value");
System.out.println(result); //
Output: Default Value
// Using ifPresent
optional.ifPresent(value ->
System.out.println("Value: " + value)); // Does nothing
3.
Using map and flatMap
Optional<String> optional =
Optional.of("Hello");
Optional<Integer>
lengthOptional = optional.map(String::length);
lengthOptional.ifPresent(System.out::println);
// Output: 5
Benefits of
Optional:
- Eliminates the risk of NullPointerException.
- Promotes functional programming by using methods
like map, flatMap, and ifPresent.
- Makes the code more expressive and easier to
understand.
No comments:
Post a Comment