2

i have to convert an Option to Optional, and created the code for this but i believe it could be even shorter that the private method is not used.

Optional<Long> optionalLong  ;
 Optional<Instant> optionalInstant;


assertThat(createdOrder.acceptedTime, is( OptionalLongToOptionalInstant(expectedOrder.acceptedTime())));


private Optional<Instant> OptionalLongToOptionalInstant(Optional<Long> optionalLong ) {
    if(optionalLong.isPresent()){
        return   Optional.of(Instant.ofEpochMilli(optionalLong.get()));
    }
    return Optional.empty();
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • How oome `acceptedTime()` doesn’t return an [`OptionalLong`](https://docs.oracle.com/javase/10/docs/api/java/util/OptionalLong.html)? – Ole V.V. Nov 06 '19 at 18:17

2 Answers2

4

You should use Optional.map() method:

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

Optional<Long> optionalLong  = Optional.ofNullable(createdOrder.acceptedTime());
Optional<Instant> optionalInstant = optionalLong.map(Instant::ofEpochMilli);
Naman
  • 27,789
  • 26
  • 218
  • 353
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
1

The .map() method is what you need

assertThat(createdOrder.acceptedTime, is(expectedOrder.acceptedTime().map(Instant::ofEpochMilli)));

Source code, it does check for you the isPresent() :

public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent()) {
        return empty();
    } else {
        return Optional.ofNullable(mapper.apply(value));
    }
}
azro
  • 53,056
  • 7
  • 34
  • 70