Java8 Optional fire one method if null , another if not null Best Approach
<p>I have A string and B string , app prefers A if not null, and call transformation method <code>changeA()</code>. However if A is null , it will use B and invoke method <code>changeB()</code> . Both transformation method return same object type <code>Result</code>. However one thing to note is that str B might null too, then if that case return null instead.</p>

<p>How do I approach this using optional and lambda expression in JDK.</p>

<p>I have the following codebase:</p>

<pre><code>changeA(){
..
}

changeB(){
..
}

aMethod(){
    Optional&lt;String&gt; optA=Optional.ofNullable(a);
    Result result = optA.map( aStr -&gt; this.changeA( aStr ) ).orElse( this.changeB( bStr ) );
}
</code></pre>

<p>This looks a bit weird cause the orElse method is using variable not within the scope of the lambda. May I know the best approach to this ?</p>

<hr>

<p>Perhaps I should state why I chose Optional. I want my team's developer to understand that even though String A is preferred , it might be null and must be handled since the part of the code is sensitive . String B is used for legacy part of the records only. Hopefully this clarify my intention on this approach. </p>