I have a number of functions:
String first(){}
String second(){}
...
String default(){}
Each can return a null value, except the default. <
If you are using java 8 you can convert these function calls to lambdas.
public static T firstNonNull(Supplier defaultSupplier, Supplier... funcs){
return Arrays.stream(funcs).filter(p -> p.get() != null).findFirst().orElse(defaultSupplier).get();
}
If you don't want the generic implementation and use it only for Strings go on and just replace T with String:
public static String firstNonNull(Supplier defaultSupplier, Supplier... funcs){
return Arrays.stream(funcs).filter(p -> p.get() != null).findFirst().orElse(defaultSupplier).get();
}
And then call it like:
firstNonNull(() -> getDefault(), () -> first(arg1, arg2), () -> second(arg3));
P.S. btw default is a reserved keyword, so you cannot use it as a method name :)
EDIT: ok, the best way to do this would be to return Optional, then you don't need to pass default supplier separetely:
@SafeVarargs
public static Optional firstNonNull(Supplier... funcs){
return Arrays.stream(funcs).filter(p -> p.get() != null).map(s -> s.get()).findFirst();
}