Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is null after each method call

Tags:

java

java-8

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
like image 691
Leonardo Avatar asked Oct 31 '17 10:10

Leonardo


2 Answers

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;
        }
    }
like image 85
Admit Avatar answered Oct 07 '22 06:10

Admit


The question explicitly mentions Java 8, but also mentions the "latest features". As it isn't clear which the OP wants, this answer is with the latest features.

With Java 9 you can use the new Optional.or method to concisely implement this logic:

import static java.util.Optional.ofNullable;
...
String x = ofNullable(methodCall())
    .or(() -> ofNullable(method2()))
    .or(() -> ofNullable(method3()))
    .or(() -> ofNullable(method4()))
    .orElse(null);

Depending on what you are doing, you might want to omit the .orElse(null).

like image 23
Reinstate Monica Avatar answered Oct 07 '22 06:10

Reinstate Monica