Optional class:

In Java 8 and later versions, the Optional class was introduced in the java.util package. The Optional class is designed to provide a more expressive and safer way to handle potentially nullable values, reducing the risk of NullPointerExceptions in certain scenarios.

Note:-Optional class is used to solve NullPointerExceptions

Example: Without using Optional class





1.Creation of Optional:

You can create an Optional instance with a non-null value using Optional.of(value).

For potentially nullable values, you can use Optional.ofNullable(value)

i.Optional<String> nonNullOptional = Optional.of("Hello");

ii.Optional<String> nullableOptional = Optional.ofNullable(null);

2.Accessing Values:

i.get(): Returns the value if present; otherwise, throws NoSuchElementException.

ii.orElse(T other): Returns the value if present; otherwise, returns the specified default value.

iii.orElseGet(Supplier<? extends T> supplier): Returns the value if present; otherwise, returns the result produced by the specified supplier.

iv.orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the value if present; otherwise, throws an exception produced by the specified supplier.

Sring  optionalValue = optional.get();

String result = optionalValue.orElse("Default Value");

String resultWithSupplier = optionalValue.orElseGet(() -> generateDefaultValue());

String valueOrThrow = optionalValue.orElseThrow(() -> new IllegalStateException("Value is absent"));

3.Checking Presence:

i.isPresent(): Returns true if a value is present; otherwise, returns false.

ii.ifPresent(Consumer<T> consumer): If a value is present, performs the given action; otherwise, does nothing.

Optional<String> optionalValue = Optional.of("Hello");
if (optionalValue.isPresent()) {
    System.out.println("Value is present: " + optionalValue.get());
}

optionalValue.ifPresent(value -> System.out.println("Value is present: " + value));

4.Conditional Actions:

i.filter(Predicate<? super T> predicate): If a value is present and satisfies the given predicate, returns an Optional describing the value; otherwise, returns an empty Optional.

ii.map(Function<? super T, ? extends U> mapper): If a value is present, applies the provided mapping function to it and returns an Optional describing the result; otherwise, returns an empty Optional.

iii.flatMap(Function<? super T, Optional<U>> mapper): If a value is present, applies the provided Optional-bearing mapping function to it and returns that result; otherwise, returns an empty Optional.

Optional<String> optionalValue = Optional.of("Hello");
Optional<String> filteredValue = optionalValue.filter(value -> value.length() > 5);
Optional<Integer> length = optionalValue.map(String::length);

Example :With Optional class