Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Optional instead of if

I have problem with Optional and I don't know how to handle it.

public void check(String name) {
   if (name != null)
      doSomething(name);
   else 
      doMore();
} 

How to change this if into Optional?

like image 810
Mateusz Sobczak Avatar asked Jul 28 '17 11:07

Mateusz Sobczak


People also ask

How do I replace if else with Optional?

How to change this if into Optional? It might be better to take advantage of method overloading in this case, so that the check() method with no parameter calls doMore(), while the check() method with the @NonNull String name only accepts non-null Strings. Otherwise, follow either Eugene's or luk2302's suggestions.

How do you use Optional instead of null?

Creating Optional objects Also, by using ofNullable , you can create an Optional object that may hold a null value: Optional<Soundcard> sc = Optional. ofNullable(soundcard); If soundcard were null, the resulting Optional object would be empty.

Why is null better than Optional?

The reason why Optionals are so useful is because with Optionals it forces you to represent your data in such a way that you can't invoke a method from null . Without Optionals it's not only possible, it's extremely easy to. In other words, you avoid sloppy logic and stupid errors.


1 Answers

There is a very neat method for that, but present in jdk-9...

public void check(String name){
     Optional.ofNullable(name)
            .ifPresentOrElse(YourClass::doSomething, YourClass::doMore);
} 

assuming doSomething and doMore are static methods... If not an instance should be used, like this::doSomething or this::doMore

like image 149
Eugene Avatar answered Sep 27 '22 18:09

Eugene