问题
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
回答1:
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);
回答2:
You could do this:
final OptionalLong optionalLong = OptionalLong.of(5);
final Optional<Long> optional = Optional.of(optionalLong)
.filter(OptionalLong::isPresent)
.map(OptionalLong::getAsLong);
回答3:
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();
回答4:
This should work.
Optional<Long> returnValue = Optional.empty();
if(secondScreenHeight.isPresent()) {
returnValue = Optional.of(secondScreenHeight.getAsLong());
}
来源:https://stackoverflow.com/questions/51823194/how-to-map-an-optionallong-to-an-optionallong