懒惰地使用流调用多个服务

时间:2017-12-21 21:57:42

标签: java java-stream

如果前一次调用返回null,我怎样才能使用流来评估多个服务调用?即

Stream.of(service1(), service2(), service3())
    .filter(Objects::nonNull)
    .findFirst()
    .ifPresent(this::doSomething);

基本上我不希望所有三个服务调用都被调用,如果他们不必这样做,我很感兴趣,如果有一个更好的方法来做这个没有一堆

if(service1() != null)
...
else if(service2() != null)
...
else if(service3() != null)
...

2 个答案:

答案 0 :(得分:2)

假设service1()service2()等中的每一个都返回相同的数据类型,那么您可以提供一个lambda表达式来调用每个服务并返回该类型 - Supplier<Result>Result是该数据类型。您也可以提供方法参考。

Stream.<Supplier<Result>>of(YourService::service1, YourService::service2, YourService::service3)

Streams将懒惰地评估,因此使用方法引用可以利用这一点并将执行推迟到需要时。

    .map(supplier -> supplier.get())

执行链的其余部分可以按照您的方式工作。

    .filter(Objects::nonNull)
    .findFirst()
    .ifPresent(this::doSomething);

答案 1 :(得分:1)

这是一个完整的例子:

public class Main {
    public static void main(String[] args) {
        Stream<Supplier<String>> suppliers =
            Stream.of(() -> service1(), () -> service2(), () -> service3(), () -> service4());

        suppliers.map(Supplier::get)
                 .filter(Objects::nonNull)
                 .findFirst()
                 .ifPresent(System.out::println);
    }

    private static String service1() {
        System.out.println("service1");
        return null;
    }

    private static String service2() {
        System.out.println("service2");
        return null;
    }

    private static String service3() {
        System.out.println("service3");
        return "hello";
    }

    private static String service4() {
        System.out.println("service4");
        return "world";
    }
}
相关问题