Optional is defined as a container class in JAVA, or rather, a container with only one element is stored.
container object which may or may not contain a non-null value.
Optional class structure Optional properties
The Optional class contains two properties:
Class attribute: EMPTY Object attribute: value
The EMPTY attribute is used to store an Optional object with value null.
The value attribute is used to store non-null objects.
Optional method
Optional has two construction methods, both of which are modified by private.
private Optional() { this.value = null;}private Optional(T value) { this.value = Objects.requireNonNull(value);}The parameterless construction method is used to initialize EMPTY. Parameter constructor is used to initialize non-null objects.
Because the constructor is modified to be private, Optional can only call objects through class methods if it wants to instantiate. Optional provides three class methods.
empty: Returns the Optional object with value null of: Returns the value of non-null of Optional object of Nullable: The value of value returns the corresponding Optional object according to whether the parameter is null or not.
public static<T> Optional<T> empty() { Optional<T> t = (Optional<T>) EMPTY; return t;}public static <T> Optional<T> of(T value) { return new Optional<>(value);}public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value);}Example method introduction
| method | Parameter Type | Return type | illustrate | |
|---|---|---|---|---|
| get | none | T | value throws NoSucchElementException exception for null | |
| isPresent | none | boolean | If value is null, false will be returned | |
| ifPresent | Consumer<? super T> | void | If the Optional instance has a value, call the consumer for it, otherwise it will not be processed. | |
| filter | Predicate<? super T> | Optional<T> | If the value exists and satisfies the provided predicate, an Optional object including the value is returned; otherwise, an empty Optional object is returned | |
| map | Function<? super T, ? extends U> | Optional<U> | If the value exists, the provided mapping function call is executed on the value, and the Optional<U> object is returned. | |
| flatMap | Function<? super T, Optional<U>> | Optional<U> | If the value exists, the provided mapping function call is executed on the value, returning a non-null Optional object. | |
| orElse | T | T | Return it if there is a value, otherwise return a default value | |
| orElseGet | Supplier<? extends T> | T | Returns the value if there is a value, otherwise returns a value generated by the specified Supplier interface | |
| orElseThrow | Supplier<? extends X> | <X extends Throwable> | Return it if there is a value, otherwise an exception generated by the specified Supplier interface is thrown | |