I am trying to avoid isPresent
checks in my code below, but the compiler emits an error with the message
"No instance(s) of type variable(s)
U
exist so thatvoid
conforms toU
"
on the call to printAndThrowException
. This is my code:
values.stream()
.filter(value -> getDetails(value).getName.equals("TestVal"))
.findFirst()
.map(value -> printAndThrowException(value))
.orElseThrow(new Exception2("xyz"));
The method in question printAndThrowException has the below signature:
void printAndThrowException(Pojo value)
The above method always throws an exception of type RuntimeException
. The abovementioned code isn't the exact code, just transformed my code to represent the situation.
What's the problem here and how to avoid using isPresent
when calling printAndThrowException
?
values
) and what each step in the stream pipeline returns and in which step do you get this errororElseThrow
should take a supplier. So, it will be.orElseThrow(() -> new Exception2(..))
map()
is used to convert one value to another value- not the case here - this use case seems more like a case forifPresentOrElse()
(Java 9 or later)