如果存在,如何 return 一个对象,否则 return 可选空

How to return an object if present otherwise return optional empty

我有一个对象,我正在通过 rest 调用检索它。我需要那个对象中的一个对象。

final Optional<A> aResponse = Optional.ofNullable(restTemplate.getForObject(uri, A.class));

在classA中,它里面有一个B类型的对象。无论出于何种原因,此对象都可能为 null。

我正在尝试尽可能安全地查询它,以免出现空指针异常。 我试过这样做:

  final Optional<B> bType = aResponse.map(A::getB)
           .orElseGet(() -> {
        return Optional.empty();
     });

不过好像不行。它给出以下消息:Required B but empty was inferred to Optional<T> no instances.

您不必调用 orElseGet,只需:

final Optional<B> bType = aResponse.map(A::getB);

map 已经 returns 一个 Optional 如果调用它的实例是空的。

map 的 Javadoc:

Returns: an Optional describing the result of applying a mapping function to the value of this Optional, if a value is present,otherwise an empty Optional