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

前端 未结 3 761
南方客
南方客 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 10:55

    Yes, there is:

    Arrays.asList(source1, source2, ...)
       .stream()
       .filter(s -> s != null)
       .findFirst();
    

    This is more flexible, since it returns an Optional not null in case a not-null source is found.

    Edit: If you want lazy evaluation you should use a Supplier:

    Arrays.>asList(sourceFactory::getSource1, sourceFactory::getSource2, ...)
       .stream()
       .filter(s -> s.get() != null)
       .findFirst();
    

提交回复
热议问题