Return first non-null value

前端 未结 8 1988
情歌与酒
情歌与酒 2020-12-14 07:17

I have a number of functions:

String first(){}
String second(){}
...
String default(){}

Each can return a null value, except the default. <

8条回答
  •  孤城傲影
    2020-12-14 07:50

    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();
    }
    

提交回复
热议问题