I have an instance of OptionalLong
. But one of my libraries requires an Optional<Long>
as a parameter.
How can I convert my OptionalLong
into an Optional<Long>
?
I was dreaming about something like this:
OptionalLong secondScreenHeight = OptionalLong.of(32l); // or: OptionalLong.empty()
api.setHeight(secondScreenHeight.mapToRegularOptional()); // .mapToUsualOptional does not exist
The getAsLong() method is used to get the long value present in an OptionalLong object. If the OptionalLong object doesn't have a value, then NoSuchElementException is thrown.
OptionalLong help us to create an object which may or may not contain a Long value. The isPresent() method help us to get the answer that a value is present in OptionalLong object or not. If a long value is present in this object, this method returns true, otherwise false. Syntax: public boolean isPresent()
ofNullable(T value) Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional . T. orElse(T other) Return the value if present, otherwise return other .
You could do this:
final OptionalLong optionalLong = OptionalLong.of(5);
final Optional<Long> optional = Optional.of(optionalLong)
.filter(OptionalLong::isPresent)
.map(OptionalLong::getAsLong);
I don't know simpler solutions but this will do what you need.
OptionalLong secondScreenHeight = OptionalLong.of(32l);
Optional<Long> optional = secondScreenHeight.isPresent()
? Optional.of(secondSceenHeight.getAsLong())
: Optional.empty();
api.setHeight(optional);
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