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!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- Add Text at Start and End of Each Line Notepad++ - NotepadPlusPlus
- How to Comment out Code in PowerShell Script - Powershell
- How to make a Android button act as a toggle button - Android
- How to add hours and minutes to Java Instant - Java
- PHP 301 Redirect Permanently - PHP
- Round Number up to 2 decimal places in Python - Python
- Accept Only 0-9 Numbers RegEx Example - HowTos
- Take input argument from command line in Python Programming - Python