DEV Community

Code Green
Code Green

Posted on • Edited on

1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more