slartidan
slartidan

Reputation: 21618

How to map an OptionalLong to an Optional<Long>?

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()); // .mapToRegularOptional does not exist

Upvotes: 20

Views: 11837

Answers (4)

df778899
df778899

Reputation: 10931

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();

Upvotes: 5

marstran
marstran

Reputation: 28056

You could do this:

final OptionalLong optionalLong = OptionalLong.of(5);

final Optional<Long> optional = Optional.of(optionalLong)
            .filter(OptionalLong::isPresent)
            .map(OptionalLong::getAsLong);

Upvotes: 14

Orest Savchak
Orest Savchak

Reputation: 4569

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);

Upvotes: 10

pvpkiran
pvpkiran

Reputation: 27068

This should work.

Optional<Long> returnValue = Optional.empty();
if(secondScreenHeight.isPresent()) {
      returnValue = Optional.of(secondScreenHeight.getAsLong());
}

Upvotes: 1

Related Questions