Optional in details Java 8

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.

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());
}

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.