IfPresent 正确使用

IfPresent proper use

我正在尝试在此处使用 ifPresent 但无法正常工作。

这是代码。

final Optional<GenericApiGatewayResponse> apiGatewayResponse = getQueryEventsCallResponse(apiGatewayRequest);
apiGatewayResponse.ifPresent(this::getQueryEvents);

private Optional<QueryEventsResponse> getQueryEvents(final GenericApiGatewayResponse apiGatewayResponse) {
    try {
        return Optional.of(gson.fromJson(apiGatewayResponse.getBody(), QueryEventsResponse.class));
    } catch (final Exception e) {
        log.error("QueryEventsResponseDeserializationFailure : Failure " +
                "while deserialize of QueryEvents from GenericApiGatewayResponse", e);
    }
    return Optional.empty();
}

private Optional<GenericApiGatewayResponse> getQueryEventsCallResponse(final GenericApiGatewayRequest request) {
    try {
        return Optional.of(apiGatewayClient.execute(request));
    } catch(final Exception e) {
        log.error("QueryEventsCallError : Error during invoke of QueryEvents API Gateway", e);
    }
    return Optional.empty();
}

但我希望将 ifPresent 的响应作为可选的。但是 ifPresent 不允许您 return 任何东西。

您需要使用的方法是flatMap。尝试以下操作:

Optional<GenericApiGatewayResponse> apiGatewayResponseOptional = getQueryEventsCallResponse(apiGatewayRequest);
Optional<QueryEventsResponse> queryEventsResponseOptional = apiGatewayResponseOptional.flatmap(this::getQueryEvents);

Optional.ifPresent() 是当可选值存在于存储在该可选值中时添加效果的方法。它不能有任何 return 值,因为在 Java 中你不能通过 return 值重载方法 -> 因此它坚持 void 并且只允许你做像打印 [=13 这样的副作用=] 例如包含值。

您仍然可以使用:

if (!optional.isEmpty()) {
    this.getQueryEvents(optional.get())
}

或:

optional.flatMap(containedVal -> this.getQueryEvents(containedVal));