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

半城伤御伤魂 提交于 2019-12-09 15:15:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!