I have this simple fragment that I would like to reengineer in a more elegant way maybe with the latest JDK 8 features:
String x = methodCall();
if(x==null) {x=method2();}
if(x==null) {x=method3();}
if(x==null) {x=method4();}
// doing calculation with X
You can use Streams:
Optional<String> result= Stream.<Supplier<String>>of(this::method1, this::method2, this::method3)
.map(Supplier::get)
.filter(Objects::nonNull)
.findFirst();
System.out.println(result.isPresent());
The above code is equal to this (generated with Intellij Idea)
Optional<String> result = Optional.empty();
for (Supplier<String> stringSupplier : Arrays.<Supplier<String>>asList(this::method1, this::method2, this::method3)) {
String s = stringSupplier.get();
if (s != null) {
result = Optional.of(s);
break;
}
}
The question explicitly mentions Java 8, but also mentions the "latest features". As it isn't clear which the OP wants, this answer is with the latest features.
With Java 9 you can use the new Optional.or
method to concisely implement this logic:
import static java.util.Optional.ofNullable;
...
String x = ofNullable(methodCall())
.or(() -> ofNullable(method2()))
.or(() -> ofNullable(method3()))
.or(() -> ofNullable(method4()))
.orElse(null);
Depending on what you are doing, you might want to omit the .orElse(null)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With