Optional
were introduced in Java 8 version as part of the java.util package. It is designed to provide a more explicit and safer way to handle null
value instead of applying multiple null checks. The main purpose of Optional
is to eliminate null pointer exceptions and make your code more readable and expressive.
Table of Contents
Example to demonstrate null check vs Optional
Example 1: Return Value start with “p”
Without Java 8 and Optional
List<String> list = Arrays.asList("prakash","kumar","prakash","java");
String result = null;
for(String s : list){
if(s.startsWith("p")){
System.out.println(s);
result=s;
break;
}
}
if (result != null) {
System.out.println(result);
}else{
System.out.println("no found");
}
With Java 8 and Optional orElse():
List<String> list = Arrays.asList("prakash","kumar","prakash","java");
Optional<String> str = list.stream().filter(s->s.startsWith("p")).findFirst();
String s = str.orElse("no value found");
System.out.println(s);
With Java 8 and Optional isPresent():
Optional<String> str = list.stream().filter(s->s.startsWith("p")).findFirst();
String s = str.isPresent() ? str.get() : "No name found";
System.out.println(s);
Example 2: Find Address details
public String getUserAddress(String username) {
User user = userRepository.findByUsername(username);
if (user != null) {
Address address = user.getAddress();
if (address != null) {
return address.getFullAddress();
} else {
return "Address not available";
}
} else {
return "User not found";
}
}
import java.util.Optional;
public String getUserAddress(String username) {
Optional<User> userOptional = Optional.ofNullable(userRepository.findByUsername(username));
return userOptional.flatMap(User::getAddress)
.map(Address::getFullAddress)
.orElse("User or address not found");
}
Example 3: Check Employee working Status
private boolean validAddress(Employee employee)
{
if (employee != null)
{
if (employee.getAddress() != null)
{
final Instant validFrom = employee.getAddress().getValidFrom();
return validFrom != null && validFrom.isWorking(now());
}
else
return false;
}
else
return false;
}
private boolean validAddress(Employee employee)
{
Optional<Employee> employeeOptional = Optional.ofNullable(employee);
return employeeOptional.isPresent() && employee.getAddress().isPresent() && employee.getAddress().getValidFrom().isPresent() && employee.getAddress().getValidFrom().isWorking(now());
}