Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 05:37:28 Viewed : 237
The Optional
class in Java provides several methods to work with optional values. These methods help handle the presence or absence of a value in a more functional and expressive way. Here are some key methods of the Optional
class:
of
:Optional
with a non-null value.Optional<T> of(T value)
javaOptional<String> optional = Optional.of("Hello, World!");
ofNullable
:Optional
with a given value, which can be null.Optional<T> ofNullable(T value)
javaString nullableValue = /* some value, possibly null */;
Optional<String> optional = Optional.ofNullable(nullableValue);
empty
:Optional
.Optional<T> empty()
javaOptional<String> emptyOptional = Optional.empty();
isPresent
:true
if the Optional
contains a value; otherwise, returns false
.boolean isPresent()
javaOptional<String> optional = /* some optional */;
if (optional.isPresent()) {
// Value is present
String value = optional.get();
// ...
} else {
// Value is absent
// ...
}
ifPresent
:void ifPresent(Consumer<? super T> consumer)
javaOptional<String> optional = /* some optional */;
String result = optional.orElse("Default Value");
orElse
:T orElse(T other)
javaOptional<String> optional = /* some optional */;
String result = optional.orElseGet(() -> computeDefaultValue());
orElseGet
:T orElseGet(Supplier<? extends T> other)
javaOptional<String> optional = /* some optional */;
String result = optional.orElseGet(() -> computeDefaultValue());
orElseThrow
:<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
javaOptional<String> optional = /* some optional */;
String result = optional.orElseThrow(() -> new RuntimeException("No value present"));
filter
:Optional
describing the value, if the predicate is true, otherwise returns an empty Optional
.Optional<T> filter(Predicate<? super T> predicate)
javaOptional<String> optional = /* some optional */;
Optional<String> filtered = optional.filter(value -> value.startsWith("H"));
map
:Optional
describing the result, otherwise returns an empty Optional
.<U> Optional<U> map(Function<? super T, ? extends U> mapper)
javaOptional<String> optional = /* some optional */;
Optional<Integer> length = optional.map(String::length);
flatMap
:Optional
.<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)
javaOptional<String> optional = /* some optional */;
Optional<Character> firstChar = optional.flatMap(value -> value.isEmpty() ? Optional.empty() : Optional.of(value.charAt(0)));
These are some of the essential methods provided by the Optional
class. They help in writing more expressive and concise code when dealing with optional values, avoiding explicit null checks and promoting better error handling practices.