Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()); // .mapToUsualOptional does not exist
like image 879
slartidan Avatar asked Aug 13 '18 13:08

slartidan


People also ask

How to get long value from Optional in Java?

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.

What is optional long Java?

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

What is optional ofNullable in Java?

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 .


2 Answers

You could do this:

final OptionalLong optionalLong = OptionalLong.of(5);

final Optional<Long> optional = Optional.of(optionalLong)
            .filter(OptionalLong::isPresent)
            .map(OptionalLong::getAsLong);
like image 90
marstran Avatar answered Sep 17 '22 20:09

marstran


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);
like image 40
Orest Savchak Avatar answered Sep 17 '22 20:09

Orest Savchak