[英]How to map an OptionalLong to an Optional<Long>?
I have an instance of OptionalLong
. 我有一个
OptionalLong
的实例。 But one of my libraries requires an Optional<Long>
as a parameter. 但我的一个库需要一个
Optional<Long>
作为参数。
How can I convert my OptionalLong
into an Optional<Long>
? 如何将
OptionalLong
转换为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
You could do this: 你可以这样做:
final OptionalLong optionalLong = OptionalLong.of(5);
final Optional<Long> optional = Optional.of(optionalLong)
.filter(OptionalLong::isPresent)
.map(OptionalLong::getAsLong);
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);
One more possibility, though only from JDK 9 is via the new OptionalLong.stream()
method, which returns a LongStream
. LongStream
一种可能性,尽管仅来自JDK 9,是通过新的OptionalLong.stream()
方法,它返回一个LongStream
。 This can then be boxed to a Stream<Long>
: 然后可以将其装箱为
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: 使用JDK 8,可以通过逐步使用Guava中的Streams实用程序类来完成类似的操作:
Optional<Long> optional = Streams.stream(optionalLong).boxed().findFirst();
This should work. 这应该工作。
Optional<Long> returnValue = Optional.empty();
if(secondScreenHeight.isPresent()) {
returnValue = Optional.of(secondScreenHeight.getAsLong());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.