Optional.ofNullable and method chaining
<p>I was surprised by <code>Optional.ofNullable</code> method. Some day I wrote a function that supposed to return an Optional:</p>

<pre><code>private Optional&lt;Integer&gt; extractFirstValueFrom(InsightsResponse insight) {
    return Optional.ofNullable(insight.getValues().get(0).getValue());
}
</code></pre>

<p>I mistakenly thought that <code>Optional.ofNullable</code> will prevent any <code>NullPointerExceptions</code> inside of argument expression. </p>

<p>Now I think I know that it was very foolish idea. Java have to resolve arguments first to pass it to <code>Optional.ofNullable</code> invocation.</p>

<p>But I have a question. Is there a nice and good way to accomplish my goal? I would like to obtain from expression <code>insight.getValues().get(0).getValue()</code> some Integer value or null. Null can be each one of the expressions: <code>insight.getValues()</code> or <code>insight.getValues().get(0)</code>.</p>

<p>I know that I can just put this in try/catch block but I am wondering if there is more elegant solution.</p>