I have an instance of OptionalLong
. But one of my libraries requires an Optional
as a parameter.
How can I convert my Option
You could do this:
final OptionalLong optionalLong = OptionalLong.of(5);
final Optional<Long> optional = Optional.of(optionalLong)
.filter(OptionalLong::isPresent)
.map(OptionalLong::getAsLong);
This should work.
Optional<Long> returnValue = Optional.empty();
if(secondScreenHeight.isPresent()) {
returnValue = Optional.of(secondScreenHeight.getAsLong());
}
One more possibility, though only from JDK 9 is via the new OptionalLong.stream()
method, which returns a LongStream
. This can then be boxed to a Stream<Long>
:
OptionalLong optionalLong = OptionalLong.of(32);
Optional<Long> optional = optionalLong.stream().boxed().findFirst();
With JDK 8 something similar can be done, by stepping out to the Streams utility class in Guava:
Optional<Long> optional = Streams.stream(optionalLong).boxed().findFirst();
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);