Avoid NoSuchElementException with Stream
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;
Stream#findFirst()
returns an Optional
which exists specifically so that you don't need to operate on null
values.
A container object which may or may not contain a non-null value. If a value is present,
isPresent()
will returntrue
andget()
will return the value.
Otherwise, Optional#get()
throws a NoSuchElementException
.
If a value is present in this
Optional
, returns the value, otherwise throwsNoSuchElementException
.
An Optional
will never expose its value if it is null
.
If you really have to, just check isPresent()
and return null
yourself.
Stream<T> stream = stream();
Optional<T> result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst();
if (result.isPresent())
return result.get();
return null;