Skip to content
Advertisement

How to map an OptionalLong to an Optional?

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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement