Is there an elegant way to get the first non null value of multiple method returns in Java?

前端 未结 3 793
南方客
南方客 2021-02-08 10:06

You have already seen this many times yourself, of that I\'m sure:

public SomeObject findSomeObject(Arguments args) {
    SomeObject so = queryFirstSource(args);         


        
3条回答
  •  自闭症患者
    2021-02-08 11:02

    I would write it like this (you may not need generics here but why not do it):

    public static  Optional findFirst(Predicate predicate, A argument,
                                             Function... functions) {
      return Arrays.stream(functions)
              .map(f -> f.apply(argument))
              .filter(predicate::test)
              .findFirst();
    }
    

    And you can call it with:

    return findFirst(Objects::nonNull, args, this::queryFirstSource,
                                           this::querySecondSource,
                                           this::queryThirdSource);
    

    (assuming your queryXXX methods are instance methods)

    The methods will be applied in order until one returns a value that matches the predicate (in the example above: returns a non null value).

提交回复
热议问题