Please wait...

小波Note

四川 · 成都市11 ℃
English

Java Optional

成都 (cheng du)8/27/2024, 5:50:17 PM3.81kEstimated reading time 12 minFavoriteCtrl + D / ⌘ + D
cover
IT FB(up 主)
Back-end development engineer

Optional is a container class introduced in Java 8 that represents an object that may or may not contain a non-null value. It is primarily used to avoid NullPointerException and provide a more elegant way to handle null values. Here are some common usage examples of Optional.

Creating Optional objects

Optional.of(value): Creates an Optional object containing a non-null value.

Optional.ofNullable(value): Creates an Optional object that may contain a null value.

Optional.empty(): Creates an empty Optional object.

Checking if Optional contains a value

isPresent(): Returns true if the Optional contains a value.

ifPresent(Consumer<? super T> action): Performs the given action if the Optional contains a value.

Getting the value of Optional

get(): Returns the value if the Optional contains a value, otherwise throws NoSuchElementException.

orElse(T other): Returns the value if the Optional contains a value, otherwise returns the default value.

orElseGet(Supplier<? extends T> other): Returns the value if the Optional contains a value, otherwise calls the Supplier and returns its result.

orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the value if the Optional contains a value, otherwise throws the exception provided by the Supplier.

Transforming the value of Optional

map(Function<? super T, ? extends U> mapper): Applies the mapping function and returns a new Optional if the Optional contains a value.

flatMap(Function<? super T, Optional<U>> mapper): Similar to map, but the mapping function returns an Optional and does not nest Optional.

Example

java
        import java.util.Optional;

public class OptionalExamples {

    public static void main(String[] args) {
        // Create Optional objects
        Optional<String> nonEmptyOptional = Optional.of("Hello, World!");
        Optional<String> nullableOptional = Optional.ofNullable(null);
        Optional<String> emptyOptional = Optional.empty();

        // Check if Optional contains a value
        System.out.println("nonEmptyOptional is present: " + nonEmptyOptional.isPresent());
        System.out.println("nullableOptional is present: " + nullableOptional.isPresent());
        System.out.println("emptyOptional is present: " + emptyOptional.isPresent());

        // Get the value of Optional
        System.out.println("nonEmptyOptional value: " + nonEmptyOptional.get());
        System.out.println("nullableOptional value or default: " + nullableOptional.orElse("Default Value"));
        System.out.println("emptyOptional value or default: " + emptyOptional.orElse("Default Value"));

        // Perform an action using ifPresent
        nonEmptyOptional.ifPresent(value -> System.out.println("Value is present: " + value));

        // Transform the value of Optional
        Optional<Integer> lengthOptional = nonEmptyOptional.map(String::length);
        System.out.println("Length of nonEmptyOptional value: " + lengthOptional.orElse(0));

        // Handle nested Optional using flatMap
        Optional<Optional<String>> nestedOptional = Optional.of(Optional.of("Nested Value"));
        Optional<String> flatMappedValue = nestedOptional.flatMap(opt -> opt);
        System.out.println("FlatMapped value: " + flatMappedValue.orElse("No Value"));
    }
}