Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return if optional is present and continue if not

Tags:

java

java-8

I have a optional method which returns Cat object (which is a optional). From the place I call It i would like to handle it in a way if cat is present then return otherwise continue

Opitional<Cat> option = isCatFound();
if (option.isPresent()) {
return option.get();
}
//DO STUFF HERE IF NO CAT FOUND

The above code is what I have now. I like to use something better than that, a single line solution.

Is there such possibility ? or correct way to use Optional ?

like image 476
dinesh707 Avatar asked Aug 31 '15 12:08

dinesh707


People also ask

How can I return optional value in Java?

Optional<String> value = Optional. of(str[ 2 ]); // It returns value of an Optional.

How do you check Optional is empty or not?

Once you have created an Optional object, you can use the isPresent() method to check if it contains a non-null value. If it does, you can use the get() method to retrieve the value. Developers can also use the getOrElse() method, which will return the value if it is present, or a default value if it is not.

How do you find the optional value of a present?

Retrieving the value using get() method Optional's get() method returns a value if it is present, otherwise it throws NoSuchElementException. You should avoid using get() method on your Optionals without first checking whether a value is present or not, because it throws an exception if the value is absent.


2 Answers

The Optional class provides a method for exactly that purpose: orElseGet(Supplier). So, with some little helper method you can do this:

Optional<Cat> option = isCatFound();
return option.orElseGet(this::noCatFound);

private Cat noCatFound() {
    // do whatever is appropriate here
    return null;
}

Of course, you could move the helper method's body into a lambda exprssion that feeds the orElseGet method.

like image 104
Seelenvirtuose Avatar answered Oct 18 '22 08:10

Seelenvirtuose


Since your method has to return a value of that type at the end, you could use

Optional<Cat> option = isCatFound();
return option.orElseGet(() -> {
  // DO STUFF HERE IF NO CAT FOUND
  // WHICH WILL EVENTUALLY RETURN A VALUE
};

If your “stuff if no cat found” fits into a single line, it might be an option. Otherwise I don’t see any advantage over your original code. Especially as it has the disadvantage that the alternative code path can’t throw checked exceptions any more.

like image 25
Holger Avatar answered Oct 18 '22 10:10

Holger