Recipes for Optional
Optional allows us to wrap a nullable object in it so we can make a method to return Optional instead of bare object. There is a possibility that below method can return null; so we need to explicitly do the null check on the returned object before using it.
Check below modified method which returns Optional
I will go through some recipes to handle Optional results, before that lets create an EmployeeService which returns Employee object.
Recipe 1: Check if result is present in the Optional using isPresent() and if it present then get the result using get() function.
Its not a good practice to use isPresent and get methods because this code is doing regular null check and then performing action on it. Instead follow the next recipes which will show you different ways to use Optional result. I used these methods to show available functions in the Optional class.
Recipe 2: Consume the result with out checking null. ifPresent() takes a consumer and it is executed only if the result is not null. We no need to explicitly check the null.
Recipe 3: Consume and perform action if the result is present and if not present then perform empty action. ifPresentOrElse function takes two parameters, first parameter is consumer which will be executed if the result is present and second parameter is a runnable which will be executed when the result is null.
Recipe 4: Perform filter before consuming the result. Filter function takes predicate and returns Optional. We can test the result before processing. Filter function returns empty Optional if predicate returns false.
Recipe 5: If result is present then perform action on it else perform action by creating new Optional. If getEmployee did not return Employee then we can create and return empty Employee. Other alternatives to this function is orElse(T other), orElseGet(Supplier<? extends T> supplier) both of these functions returns T instead of Optional
Recipe 6: Throw exception if result is not present. orElseThrow takes supplier which should return throwable object.
Recipe 7: We can map the result to different type with map function. For example using map we can extract employee age from the employee object. The returned employee age from the map is wrapped in its own Optional. So make sure to unwrap it before using.
Recipe 8: Alternative to map is flatMap function. Both of these functions returns Optional except in flatMap we need to explicitly map to Optional.