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?
NoSuchElementException in Java can come while using Iterator or Enumeration or StringTokenizer. Best way to fix NoSuchElementException in java is to avoid it by checking Iterator with hashNext(), Enumeration with hashMoreElements() and StringTokenizer with hashMoreTokens().
Cause for NosuchElementException If you call the nextElement() method of the Enumeration class on an empty enumeration object or, if the current position is at the end of the Enumeration, a NosuchElementException is generated at run time.
It is be cause NoSuchElementException is unchecked exception, which means that it "is-a" RuntimeException which does not force you to catch. The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses.
Optional get() method in Java with examples If there is no value present in this Optional instance, then this method throws NullPointerException. Parameters: This method do not accept any parameter. Return value: This method returns the value of this instance of the Optional class.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With