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.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay