Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to use a Java 8 Optional method that either gets the wrapped value, or calls a void return Consumer lambda

I am new to using optionals in Java 8. I know the method orElseGet() takes a supplier and orElseThrow() also takes a supplier that throws an exception. orElseThrow() might be a good one to use if I can construct my own exception and do something when that exception is triggered.

My main goal is to use a method that will either get the unwrapped value, or if the optional wraps null, then to actually execute an entirely different function.

Looking for the closest thing to:

class DoInsteadClass {
     public void doInstead() {
          // Do this instead
     }
}


Optional<String> myString = "Hello";
num.orElse(DoInsteadClass::doInstead);

If the only way to do this is orElseThrow(), and as long as I can handle the exception with the 'do this instead' code, that should be fine too. It just makes my codebase larger because I have to create a few different custom utility suppliers for the 2 or 3 cases where some of my optional values would return null.

The problem is, .ifPresent() invokes the specified consumer with the value, otherwise does nothing. I need it to DO SOMETHING if the value is null. My current code utilizes a custom workaround where I first check if the value is null, and if it is, execute a chosen function. Then the next statement is the one that checks for ifPresent(). So this is doing the same thing, I am just looking for a more sugar-coated, one statement version.

like image 548
TyRyDurden Avatar asked Apr 14 '17 18:04

TyRyDurden


People also ask

What is the purpose benefit of using optional in Java 8?

So, to overcome this, Java 8 has introduced a new class Optional in java. util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run.

How do I set optional value in Java?

You can create an Optional object using the of() method, which will return an Optional object containing the given value if the value is non-null, or an empty Optional object if the value is null.

What is optional method in Java?

Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.


1 Answers

In JDK 9 there will be an ifPresentOrElse method that will allow it.
For the time being, however, you may opt for the if statement, with if(num.isPresent()), or write your own reusable ifPresentOrElse method.

like image 123
Grzegorz Górkiewicz Avatar answered Sep 22 '22 16:09

Grzegorz Górkiewicz