Prakhar
Prakhar

Reputation: 536

IfPresent proper use

I am trying to use ifPresent here but not able to get it working.

Here is the code.

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();
}

But I want to get response of ifPresent as Optional. But ifPresent does not allow you to return anything.

Upvotes: 1

Views: 96

Answers (2)

Norbert Dopjera
Norbert Dopjera

Reputation: 751

Optional.ifPresent() is method to add effect when optional is present over value that is stored inside that optional. It cannot have any return value since in Java you can't overload method's by return value -> therefore it stick's with void and only allow's you to do side effect like printing Optional contained value for example.

You can still use:

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

or:

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

Upvotes: 0

Utku &#214;zdemir
Utku &#214;zdemir

Reputation: 7725

The method you need to use is flatMap. Try the following:

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

Upvotes: 2

Related Questions