Check if object is null after each method call

Leonardo :

I have this simple fragment that I would like to reengineer in a more elegant way maybe with the latest JDK 8 features:

String x = methodCall();
if(x==null) {x=method2();}
if(x==null) {x=method3();}
if(x==null) {x=method4();}

// doing calculation with X
Admit :

You can use Streams:

    Optional<String> result= Stream.<Supplier<String>>of(this::method1, this::method2, this::method3)
            .map(Supplier::get)
            .filter(Objects::nonNull)
            .findFirst();
    System.out.println(result.isPresent());

The above code is equal to this (generated with Intellij Idea)

    Optional<String> result = Optional.empty();
    for (Supplier<String> stringSupplier : Arrays.<Supplier<String>>asList(this::method1, this::method2, this::method3)) {
        String s = stringSupplier.get();
        if (s != null) {
            result = Optional.of(s);
            break;
        }
    }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459291&siteId=1