Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional ofNullable execution flow in java 8

Tags:

java

java-8

I have noticed that if I use Optional the following way:

Object returnValue = Optional.ofNullable(nullableValue)
         .map(nonNullValue -> firstMethod(arg1, nonNullValue))
         .orElse(secondMethod)

It is executing both the first method and second method when the nullableValue is not null. Am I doing something wrong? I want it to execute only firstMethod when nullableValue is not null.

map and flatMap seems to have preCondition ( if(!isPresent()). but, orElse doesn't. How can I write my code using java8 without using if not null condition?

Based on comments, sample code:

public static String firstMethod(String someString) {
        System.out.println("In first method");
        return someString;
    }

    public static String secondMethod() {
        System.out.println("In second method");
        return "secondMethod";
    }

    public static void main(String a[]) {
        String nullableString = "nonNullString";
        String result = Optional.ofNullable(nullableString)
                .map(nonNullString -> firstMethod(nonNullString))
                .orElse(secondMethod());
        System.out.println("Result: "+result);
    }

Output:

In first method
In second method
Result: nonNullString
like image 315
would_like_to_be_anon Avatar asked Feb 13 '23 03:02

would_like_to_be_anon


1 Answers

You are calling the second method to pass as a parameter to the orElse() call. The orElse() is not the one calling secondMethod() like what happens in the map call. You are passing the returned value from secondMethod() not the method itself.

What you want to do:

Optional.ofNullable(nullableValue).map(MyClass::firstMethod).orElseGet(MyClass::secondMethod);

What this does it is casts secondMethod into a supplier. That way it is only called when the optional is null.

like image 114
Strikeskids Avatar answered Feb 15 '23 09:02

Strikeskids