Avoid NoSuchElementException with Stream

clankill3r picture clankill3r · Jun 6, 2015 · Viewed 68.5k times · Source

I have the following Stream:

Stream<T> stream = stream();

T result = stream.filter(t -> {
    double x = getX(t);
    double y = getY(t);
    return (x == tx && y == ty);
}).findFirst().get();

return result;

However, there is not always a result which gives me the following error:

NoSuchElementException: No value present

So how can I return a null if there is no value present?

Answer

Tagir Valeev picture Tagir Valeev · Jul 14, 2015

You can use Optional.orElse, it's much simpler than checking isPresent:

T result = stream.filter(t -> {
    double x = getX(t);
    double y = getY(t);
    return (x == tx && y == ty);
}).findFirst().orElse(null);

return result;