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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay