You need to be clear about what you expect of your method. Possibilities:
- You want it to keep working as before, and handle the case where the client supplies a null
- You want to change the method to accept
Optional<Integer>
as its parameter. The "no nulls" way, is to do this, and simply not accommodate callers who supply null -- if they get a NullPointerException, it's their own fault because they broke the rules.
You don't have to work with streams or lambdas to work with Optional (although of course, you can).
You could simply write:
public List<T> getAll(Optional<Integer> maybeParameter) {
if(maybeParameter.isPresent() && maybeParameter.get() > -1) {
// do something here
}
}
Look at Optional
's other methods in JavaDoc, to see how else it can be used.
If you didn't want to change the signature of your method, you could use Optional.ofNullable()
to turn an Integer
into an Optional<Integer>
:
public List<T> getAll(Integer parameter) {
Optional<Integer> maybeParameter = Optional.ofNullable(parameter);
// work with the Optional here as before...
}
However I question the value of doing this here. If your API accepts nulls, then handling it with Optional
"behind the scenes" doesn't provide an advantage.
I feel the best use of Optional
is to expose it as part of your API. If a parameter is optional, declare it as Optional
rather than handling null (or better, use method overloading, so they don't have to pass anything at all). If a return value might not be set, make the return type Optional
, rather than ever returning null.