1. What is Optional in Java
Optional is a container object which may or may not contain a non-null value.
The Optional class can be used to represent a value instead of a null reference.
2. Methods to create Object of Optional class
- public static
Optional empty()
This method returns an empty Optional instance.
Example:Optional<String> optionalString = Optional.empty(); Optional<Integer> optionalInteger = Optional.empty(); Optional<Employee> optionalEmployee = Optional.empty();
- public static
Optional of(T value)
This method returns an Optional value for the given non-null value.
It is important to note that the value provided as an argument to this method is non-null, or else you will get a NullPointerException while performing operations on it if the value is null.
Example:String strValue = "Code2care"; Optional
optionalString = Optional.of(strValue); Integer intValue = 20; Optional optionalInteger = Optional.of(intValue); Employee empValue = new Employee(1, "Sam","IT"); Optional optionalEmployee = Optional.of(empValue); - public static
Optional ofNullable(T value)
This method returns an Optional for the given value, if it is non-null, or else returns an empty Optional.
Example:String strValue = "Code2care"; Optional
optionalString = Optional.ofNullable(strValue); Integer intValue = 20; Optional optionalInteger = Optional.ofNullable(intValue); Employee empValue = new Employee(1, "Sam","IT"); Optional optionalEmployee = Optional.ofNullable(empValue);
There are 3 static that you can make use of to get an Optional object.
3. How to Get Values from an Optional Object
- get() Method:
Use the get() method to retrieve the value if it is present. Note that if the value is absent (empty), it will throw a NoSuchElementException. It's recommended to use this method only when you are certain the value is present.
Example:Optional<String> optionalString = Optional.of("Code2care"); String value = optionalString.get();
- orElse(T defaultValue) Method:
Use the orElse(T defaultValue) method to get the value if present, or provide a default value if the Optional is empty.
Example:Optional<Integer> optionalInteger = Optional.ofNullable(20); Integer value = optionalInteger.orElse(0);
- orElseGet(Supplier<? extends T> supplier) Method:
Use the orElseGet method to get the value if present, or provide a Supplier that generates a default value if the Optional is empty.
Example:Optional<Employee> optionalEmployee = Optional.empty(); Employee defaultValue = optionalEmployee.orElseGet(() -> new Employee(0, "Default", "DefaultDept"));
- orElseThrow() and orElseThrow(Supplier<? extends X> exceptionSupplier) Methods:
Use orElseThrow() to get the value if present or throw NoSuchElementException if empty.
Use orElseThrow(Supplier<? extends X> exceptionSupplier) to throw a custom exception if empty.
Optional<Employee> optionalEmployee = Optional.of(new Employee(1, "Sam", "IT")); Employee value = optionalEmployee.orElseThrow();
Below are the methods from the Optional class that you can make use of to get value from an Optional type.
4. Optional with Lambda and Stream API
- Optional with Lambda and Stream:
You can make use of Lambda expressions and Streams with Optional to express code in a clean way.
Examples:Optional<String> optionalString = Optional.of("Code2care"); optionalString.ifPresent(value -> System.out.println("Value is present: " + value));
Optional<Integer> optionalInteger = Optional.ofNullable(20); Optional<String> transformedValue = optionalInteger .filter(value -> value > 10) .map(value -> "Transformed: " + value);
Optional<Employee> optionalEmployee = Optional.of(new Employee(1, "Sam", "IT")); String department = optionalEmployee .map(Employee::getDepartment) .orElseGet(() -> getDepartmentFromDatabase());
Facing issues? Have Questions? Post them here! I am happy to answer!
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
- Python: Pandas Rename Columns with List Example - Python
- How to get file path of a file using Java Code? - Java
- Quick Fix: How to Force Restart Your iPhone - iOS
- Python: Pandas Merge With Examples - Python
- Java 8 Predicate Functional Interface isEqual() Method Example - Java
- Enable Spellcheck in eclipse workspace - Eclipse
- PHP Fatal error : Call to a member function bind_param() on a non-object - PHP
- Fix: pip install mysqlclient error: subprocess-exited-with-error - MySQL