1 min read

Java Tips: Optional - anything better than isPresent?

Mallim

orElse() - Constant for orElse

From

public static final String DEFAULT_STATUS = "Unknown";
...
public String getEmployeeStatus(long id) {
    Optional<String> empStatus = ... ;
    if (empStatus.isPresent()) {
        return empStatus.get();
    } else {
        return DEFAULT_STATUS;
    }
}

To

public String getEmployeeStatus(long id) {
    Optional<String> empStatus = ... ;
    return empStatus.orElse(DEFAULT_STATUS); // Constant for orElse
}

orElseGet() - Function call for orElseGet

System.out.println(Optional.ofNullable(s).orElseGet(() -> {
    System.out.print("za ");
    return "warudo";
}));

orElseThrow()

From

public Inventory getInventory(User user) {
    Optional inventory = findInventoryByUser(User user)
    if (inventory.isPresent()) {
        return inventory.get();
    } else {
        throw new NotFoundException();
    }
}

To

public Inventory getInventory(User user) {
    return findInventoryByUser(User user)
        .orElseThrow(() -> new NotFoundException());
}

also

public Inventory getInventory(User user) {
    return findInventoryByUser(User user)
        .orElseThrow(NotFoundException::new);
}

Stream.findFirst()

Integer idCountry = listContries.stream()               // Stream
    .filter(c -> countryFinal.equals(c.getNoCountry())) // Get one equals to "Spain"
    .findFirst()                                        // Get Optional<Country>
    .map(Country::getCoCountry)                         // If exists, get its code
    .orElse(0);                                         // Or else return an invalid code

References