Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if is null and if has a specific value using Optional in java?

Assume that I have this code in my project:

public List<T> getAll(Integer parameter) {
    if(parameter != null && parameter > -1) {
        // do something here
    }
}

My question is: how can I do the checking with Optional instead of using if, or if there is another thing I could use?

like image 459
Rasool Ghafari Avatar asked Nov 14 '16 11:11

Rasool Ghafari


People also ask

How do you do null check for Optional in Java?

Optional was introduced to Java as a way to fix the issues with null references. Before Optional , every object was allowed to either contain a value or not (i.e. being null ). The introduction of Optional essentially enforces null -checking by the type-system making it unnecessary to perform such checks manually.

How do you use Optional class for null check?

Solution: Using Optional ClassofNullable() method of the Optional class, returns a Non-empty Optional if the given object has a value, otherwise it returns an empty Optional. We can check whether the returned Optional value is empty or non-empty using the isPresent() method.

Can an Optional object be null in Java?

Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null . It should always point to an Optional instance.


2 Answers

Optional's design was inspired by monads known from the world of Functional Programming. In such case, it could look like this:

public List<T> getAll(Integer parameter) {

    return Optional.ofNullable(parameter)
      .filter(p -> p > -1)
      .map(p -> *some modification*) //this line is optional
      .orElseGet(() -> *some default value, probably an empty list*)
}

In such case, condition checking is performed in the filter method. If a given Predicate is not matched, the underlying Optional will be empty.

If you want to perform an operation on the underlying value, use map method by providing it with a Function that should be applied to the element wrapped by the Optional.

At the end, you can simply perform some action using ifPresent(), thrown an exception orElseThrow or simply return a default value with orElse or orElseGet. Keep in mind that orElseGet accepts a Supplier instance which makes it evaluate the default value lazily.

If you want to dig deeper, check out @stuart-marks talk from Devoxx: https://www.youtube.com/watch?v=Ej0sss6cq14&t=2767s

In your case, there might be no need for an Optional at all. Just two methods. One with the parameter and the other without.

like image 162
Grzegorz Piwowarek Avatar answered Oct 09 '22 07:10

Grzegorz Piwowarek


You should not use Optional for such a case

As Stuart Marks states in Optional - The Mother of All Bikesheds:

Rule #4: It's generally a bad idea to create an Optional for the specific purpose of chaining methods from it to get a value.

This creates a useless overhead without any improvement for code readability and maintainability. You should thus not wrap your parameter into an optional.

and

Rule #6: Avoid using Optional in fields, method parameters and collections.

Avoid using Optional in method parameters

  • it doesn't really work for making parameters optional
  • forces call sites to create Optionals for everything:

    myMethod(Optional.of("some value"));

    myMethod(Optional.empty());

See also Why should Java 8's Optional not be used in arguments.

like image 35
Didier L Avatar answered Oct 09 '22 07:10

Didier L