How to map an OptionalLong to an Optional?

前端 未结 4 1957
逝去的感伤
逝去的感伤 2021-02-20 01:59

I have an instance of OptionalLong. But one of my libraries requires an Optional as a parameter.

How can I convert my Option

相关标签:
4条回答
  • 2021-02-20 02:19

    You could do this:

    final OptionalLong optionalLong = OptionalLong.of(5);
    
    final Optional<Long> optional = Optional.of(optionalLong)
                .filter(OptionalLong::isPresent)
                .map(OptionalLong::getAsLong);
    
    0 讨论(0)
  • 2021-02-20 02:26

    This should work.

    Optional<Long> returnValue = Optional.empty();
    if(secondScreenHeight.isPresent()) {
          returnValue = Optional.of(secondScreenHeight.getAsLong());
    }
    
    0 讨论(0)
  • 2021-02-20 02:33

    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();
    
    0 讨论(0)
  • 2021-02-20 02:34

    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);
    
    0 讨论(0)
提交回复
热议问题