Java 8 introduced a new class called Optional in the java.util package. Optional is a container object that may or may not contain a non-null value. It is used to represent null with an absent value and provides various utility methods to facilitate code to handle values as available or not available instead of checking null values. Optional can help in writing a neat code without using too many null checks, making the code more readable because the facts which were hidden are now visible to the developer.
Some of the methods provided by the Optional class are:
- empty(): Returns an empty Optional instance.
- filter(Predicate<? super T> predicate): If a value is present and the value matches a given predicate, it returns an Optional describing the value, otherwise returns an empty Optional.
- flatMap(Function<? super T,Optional<U>> mapper): If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional.
- get(): If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
- isPresent(): Returns true if there is a value present, otherwise false.
- of(T value): Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
- orElse(T other): Returns the value if present, otherwise returns other.
Optional can be used in various situations, such as:
- As a public method return type when the method could return null.
- As a method parameter when the parameter may be null.
- As an optional member of a bean.
- In collections.
However, it is important to note that Optional should not be overused and should only be used when it makes sense to do so. Overusing Optional can lead to additional overhead and may not add any benefits to the code.