The Optional object in Java (java.util.Optional) is a container object which may or may not have a value. Designed specifically to handle the null case in a safe and explicit way, the optionals help write more readable code.
Typical Usage
1) When returning an object that might be null
public Optional<Employee> findEmployeeByName(String name) {
Employee employee = repo.findEmployee(name);
return Optional.ofNullable(employee);
}
2) To fallback upon receiving null
-
Return a default object
Employee employee = findEmployeeByName("John") .orElse(new Employee("Unknown", 20)); -
Return after a pipeline of operators
Integer salary = findEmployeeByName("John") .map(Employee::getSalary) .orElse(30); -
Run a callback if value exists
findEmployeeByName("John") .ifPresent(employee -> { kafkaTemplate.send("employee-key", employee, "employee-topic"); }); -
Return an exception
try { value = opDouble.orElseThrow(IOException::new); } catch (IOException e) { System.out.println("Exception " + e); }By default returns
NoSuchElementException, if no value exists within the Optional.
Top comments (0)