The Stream::findAny
returns Optional
and its method Optional::findAny
, according to the documentation, there are 4 ways to return T
:
Optional::get
returns the T
or throws NoSuchElementException
Optional::orElse
returns T
or a default value
Optional::orElseGet
returns T
or a value provided with Supplier
Optional::orElseThrow
returns T
or throws a custom exception
As far as I understand, you are looking for the second or third method which returns a defined value in case the origin is null
. You can return a null-object using the Null-Object pattern which represents an object which is valid but does "nothing". Or else you can use null
.
I suggest you receive a country before you let return null
or anything alse and use getCoCountry()
method on it (I suppose Country::getCoCountry
returns either int
or Integer
) - otherwise, what have you done would return NullPointerException
.
Try the following snippet:
Integer idCountry = listContries.stream() // Stream
.filter(c -> countryFinal.equals(c.getNoCountry())) // Get one equals to "Spain"
.findFirst() // Get Optional<Country>
.map(Country::getCoCountry) // If exists, get its code
.orElse(0); // Or else return an invalid code
Note there is no need to both filter by the country name and then check the equality since you expect there is only one "Spain"
.
null
(becauseorElse(null)
), which results in a NullPointerException rather than anull
result. and b) you're casting the result to primitiveint
which can never benull
.orElse (new Object ())
...?