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.
0 Comments