If (not null && not null) Java functional programming

jdhalleine :

Before Java 8, i got used to writte my code this way

import io.vavr.control.Option;

Option<String> nullableValueA=Option.of("toto");
Option<String> nullableValueB=Option.of(null);

if (nullableValueA.isEmpty() && nullableValueB.isEmpty()){
        throw new RuntimeException("Business exception");
}

I'd like to transform this code below in a pure Java functional style with Java API or even vavr API

and doing something like this

nullableValueA.isEmpty()
.and(nullableValueB.isEmpty())
.then(
   () -> throw new RuntimeException("Business exception");
)

Any ideas of how writting this code the best way ?

Thanks a lot for your help

ernest_k :

If you're on Java 9+, you can use

String value = Optional.ofNullable("<resolve valueA>")
                .or(() -> Option.ofNullable("<resolve valueB>"))
                .orElseThrow(() -> new RuntimeException("Business exception"));

That will give you the first non-empty value, throwing an exception if both are empty.

The same thing can be achieved on Java 8 using something like:

String value = Optional.ofNullable("<resolve valueA>")
              .orElseGet(() -> Optional.ofNullable("<resolve valueB>")
                  .orElseThrow(() -> new RuntimeException("Business exception")));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31362&siteId=1