You need to clearly understand what you expect from your method. Capabilities:
- You want it to continue to work as before and handle the case when the client supplies zero
- You want to change the method to accept
Optional<Integer>
as its parameter. The "no nulls" way is to do this and simply not use callers who throw zero - if they get a NullPointerException, this is their own mistake because they break the rules.
You do not need to work with streams or lambdas to work with optional (although, of course, you can).
You can simply write:
public List<T> getAll(Optional<Integer> maybeParameter) { if(maybeParameter.isPresent() && maybeParameter.get() > -1) {
Look at Optional
other methods in the JavaDoc to find out how else this can be used.
If you do not want to change the signature of your method, you can use Optional.ofNullable()
to turn Integer
into Optional<Integer>
:
public List<T> getAll(Integer parameter) { Optional<Integer> maybeParameter = Optional.ofNullable(parameter);
However, I ask a question about how this is done here. If your API is NULL, then handling it with Optional
"behind the scenes" does not give benefits.
I find it best to use Optional
to expose it as part of your API. If the parameter is optional, declare it as Optional
, and do not handle zero (or better, use method overloading so that they donβt miss anything at all). If the return value cannot be set, enter the Optional
return type, and not return null.
source share