'Java Optional if else logic [duplicate]

I have a method that searches a customer in the DB, if found, it returns that customer, otherwise, it creates a new one.

private Customer getProjectCustomer(String customerCode) {
    Optional<Customer> customerInDB = customerRepository.findByCode(customerCode);

    if (!customerInDB.isPresent()) {
        //call to remote service to get the customer from the remote service
        Customer newCustomer = new Customer();
        ..some sets
        return customerRepository.save(newCustomer);
    }

    return customerInDB.get();
}

I have the feeling that this is not the correct way to use the Java Optional, however, I don't really know if there is a better more functional approach



Solution 1:[1]

You may use Optional.orElseGet

private Customer getProjectCustomer(String customerCode) {
    return customerRepository.findByCode(customerCode)
            .orElseGet(() -> {
                Customer newCustomer = new Customer();
                // ...
                return customerRepository.save(newCustomer);
            });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 azro