Search code examples
javajava-8java-streamoption-type

Avoid NoSuchElementException with Stream


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?


Solution

  • 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;