You can get rid of if -block using the assigned method, but also, you wonβt get it more compact. Especially you will need to check for null after each method.
Here is a method that Optional#ifPresent to apply the method if it is not:
public <V> void runIfNotPresent(V value, Runnable method) { if (value == null) { method.run(); } }
Here is your code using this method:
x = methodCall(); runIfNotPresent(x, this::method2); runIfNotPresent(x, this::method3); runIfNotPresent(x, this::method4);
Please note that you cannot directly use Optional#isPresent ( documentation ), as its logic will be canceled. However, this is also a very useful class, and if you use Java 9 , you can use Optional#or ( documentation ), as others have already shown in their answers.
Alternatively, you can write your own method for applying chain methods
public <V> V applyAsLongAsNull(V value, Function<V, V>... methods) { // Apply methods for (Function<V, V> method : methods) { if (value == null) { value = method.apply(value); } else { // Stop as soon as value is not null break; } } return value; }
Then you can convert methodX to Function<V, V> , which takes a String value and returns a possibly different String value:
public String methodX(String value) {
Finally, you will use it as:
String x = methodCall(); x = applyAsLongAsNull(x, this::method2, this::method3, this::method4);