DEV Community

Code Green
Code Green

Posted on • Edited on

Optional Class in Java and its methods

Optional Class in Java

======================

What is an Optional Class?

The Optional class in Java is a container object that may or may not contain a non-null value. It is used to avoid null pointer exceptions by providing a way to handle null values more effectively.

Available Methods in Optional Class

  • Optional.isPresent() - Checks if a value is present in the Optional.
  • Optional.get() - Gets the value from the Optional if present, otherwise throws NoSuchElementException.
  • Optional.orElse(T other) - Returns the value if present, otherwise returns the specified other value.
  • Optional.orElseGet(Supplier other) - Returns the value if present, otherwise returns the result produced by the supplying function.
  • Optional.orElseThrow(Supplier exceptionSupplier) - Returns the value if present, otherwise throws the exception produced by the supplying function.
  • Optional.ifPresent(Consumer consumer) - Executes the specified consumer if a value is present.
  • Optional.filter(Predicate predicate) - Filters the value of the Optional if present based on the specified predicate.
  • Optional.map(Function mapper) - Maps the value of the Optional if present using the specified mapper function.
  • Optional.flatMap(Function> mapper) - Maps the value of the Optional if present to another Optional using the specified mapper function.

Example

import java.util.Optional;

public class OptionalExample {

    public static void main(String[] args) {
        // Example of Optional.isPresent()
        Optional<String> optionalString = Optional.ofNullable("Hello");
        System.out.println("Is value present? " + optionalString.isPresent());

        // Example of Optional.get()
        String value = optionalString.get();
        System.out.println("Value: " + value);

        // Example of Optional.orElse()
        Optional<String> emptyOptional = Optional.empty();
        String result = emptyOptional.orElse("Default Value");
        System.out.println("Result: " + result);

        // Example of Optional.ifPresent()
        optionalString.ifPresent(val -> System.out.println("Value is present: " + val));

        // Example of Optional.map()
        Optional<Integer> optionalLength = optionalString.map(String::length);
        optionalLength.ifPresent(len -> System.out.println("Length of value: " + len));
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

The Optional class in Java provides a set of methods to handle null values effectively, reducing the chances of null pointer exceptions and improving code readability.

Top comments (0)